元組:困在牢籠的列表
阿新 • • 發佈:2020-08-11
原型模式(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) {Prototype13 this.id = id; 14 } 15 16 public abstract Prototype clone(); 17 18 }
1 public class ConcretePrototype1 extends Prototype { 2 3 public ConcretePrototype1(String id) { 4 super(id); 5 } 6 7 @Override 8 public Prototype clone() {ConcretePrototype19 Prototype pt= new ConcretePrototype1(this.getId()); 10 return pt; 11 } 12 13 }
1 public class ConcretePrototype2 extends Prototype { 2 3 public ConcretePrototype2(String id) { 4 super(id); 5 } 6 7 @Override 8 public Prototype clone() {ConcretePrototype29 Prototype pt= new ConcretePrototype2(this.getId()); 10 return pt; 11 } 12 13 }
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