DEV Community

eidher
eidher

Posted on • Edited on

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

Top comments (0)