Design Patterns (24 Part Series)
1 Main Design Patterns
2 Abstract Factory Pattern
… 20 more parts…
3 Adapter Pattern
4 Decorator Pattern
5 Strategy Pattern
6 Observer Pattern
7 Builder Pattern
8 Factory Method Pattern
9 Prototype Pattern
10 Singleton Pattern
11 Bridge Pattern
12 Composite Pattern
13 Facade Pattern
14 Flyweight Pattern
15 Proxy Pattern
16 Chain of Responsibility Pattern
17 Command Pattern
18 Interpreter Pattern
19 Iterator Pattern
20 Mediator Pattern
21 Memento Pattern
22 State Pattern
23 Template Method Pattern
24 Visitor Pattern
Specify the kind of objects to create using a prototypical instance, and create new objects by copying this prototype.
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
eidherjulian61 / design-patterns
Main Design Patterns
eidher ・ Sep 27 ’20 ・ 1 min read
#designpatterns #creational #structural #behavioral
Design Patterns (24 Part Series)
1 Main Design Patterns
2 Abstract Factory Pattern
… 20 more parts…
3 Adapter Pattern
4 Decorator Pattern
5 Strategy Pattern
6 Observer Pattern
7 Builder Pattern
8 Factory Method Pattern
9 Prototype Pattern
10 Singleton Pattern
11 Bridge Pattern
12 Composite Pattern
13 Facade Pattern
14 Flyweight Pattern
15 Proxy Pattern
16 Chain of Responsibility Pattern
17 Command Pattern
18 Interpreter Pattern
19 Iterator Pattern
20 Mediator Pattern
21 Memento Pattern
22 State Pattern
23 Template Method Pattern
24 Visitor Pattern
原文链接:Prototype Pattern
暂无评论内容