DEV Community

eidher
eidher

Posted on • Edited on

2 2

Prototype Pattern

Specify the kind of objects to create using a prototypical instance, and create new objects by copying this prototype.

Alt Text

Participants

  • Prototype: declares an interface for cloning itself
  • ConcretePrototype: implements an operation for cloning itself
  • Client: creates a new object by asking a prototype to clone itself

Code

public class Main {

    public static void main(String[] args) {
        ConcretePrototype1 p1 = new ConcretePrototype1("I");
        ConcretePrototype1 c1 = (ConcretePrototype1) p1.clone();
        System.out.println("Cloned: " + c1.getId());

        ConcretePrototype2 p2 = new ConcretePrototype2("II");
        ConcretePrototype2 c2 = (ConcretePrototype2) p2.clone();
        System.out.println("Cloned: " + c2.getId());
    }
}

public abstract class Prototype {
    private String id;

    public Prototype(String id) {
        this.id = id;
    }

    public String getId() {
        return id;
    }

    public abstract Prototype clone();
}


public class ConcretePrototype1 extends Prototype {

    public ConcretePrototype1(String id) {
        super(id);
    }

    @Override
    public Prototype clone() {
        return new ConcretePrototype1(getId());
    }
}

public class ConcretePrototype2 extends Prototype {

    public ConcretePrototype2(String id) {
        super(id);
    }

    @Override
    public Prototype clone() {
        return new ConcretePrototype2(getId()) ;
    }
}
Enter fullscreen mode Exit fullscreen mode

Output

Cloned: I
Cloned: II

Enter fullscreen mode Exit fullscreen mode

Speedy emails, satisfied customers

Postmark Image

Are delayed transactional emails costing you user satisfaction? Postmark delivers your emails almost instantly, keeping your customers happy and connected.

Sign up

Top comments (0)

A Workflow Copilot. Tailored to You.

Pieces.app image

Our desktop app, with its intelligent copilot, streamlines coding by generating snippets, extracting code from screenshots, and accelerating problem-solving.

Read the docs

👋 Kindness is contagious

Please leave a ❤️ or a friendly comment on this post if you found it helpful!

Okay