原型模式

原型模式(Prototype),用原型实例指定创建对象的种类,并通过拷贝这些原型创建新的对象。

 图示代码:

 1 public abstract class Prototype {
 2     private String id;
 3     
 4     public Prototype(String id) {
 5         this.id = id;
 6     }
 7 
 8     public String getId() {
 9         return id;
10     }
11 
12     public void setId(String id) {
13         this.id = id;
14     }
15     
16     public abstract Prototype clone();
17     
18 }
Prototype
 1 public class ConcretePrototype1 extends Prototype {
 2 
 3     public ConcretePrototype1(String id) {
 4         super(id);
 5     }
 6 
 7     @Override
 8     public Prototype clone() {
 9         Prototype pt= new ConcretePrototype1(this.getId());
10         return pt;
11     }
12 
13 }
ConcretePrototype1
 1 public class ConcretePrototype2 extends Prototype {
 2 
 3     public ConcretePrototype2(String id) {
 4         super(id);
 5     }
 6 
 7     @Override
 8     public Prototype clone() {
 9         Prototype pt= new ConcretePrototype2(this.getId());
10         return pt;
11     }
12 
13 }
ConcretePrototype2
1 public class TestPrototype {
2     public static void main(String[] args) {
3         ConcretePrototype1 c1 = new ConcretePrototype1("I");
4         ConcretePrototype1 p1 = (ConcretePrototype1) c1.clone();
5         System.out.println(p1.getId());
6     }
7 }
test
原文地址:https://www.cnblogs.com/cai170221/p/13488961.html