package Create.e.Prototype; //原型業務類 須要實現克隆接口 public class Dog implements Cloneable{ public int legCounts; public Dog(int legCounts){ this.legCounts = legCounts; } public void changeLegCounts(){ this.legCounts *= 2; } public String toString(){ return Integer.toString(this.legCounts); } @Override protected Object clone() throws CloneNotSupportedException { // TODO Auto-generated method stub Dog o = null; try{ o = (Dog)super.clone(); }catch(CloneNotSupportedException e){ e.printStackTrace(); } return o; } }
package Create.e.Prototype; //原型複製類 public class DogClone implements Cloneable { public int legCounts; public Dog dog = new Dog(4); @Override protected Object clone() throws CloneNotSupportedException { // TODO Auto-generated method stub DogClone o = null ; try{ o = (DogClone) super.clone(); }catch(CloneNotSupportedException e){ e.printStackTrace(); } o.dog = (Dog)dog.clone(); return o; } }
package Create.e.Prototype; //業務調用類 public class Client { public static void main(String[] args) throws Exception{ DogClone clone = new DogClone(); clone.legCounts = 3; System.out.println("原來克隆狗的腿數:" + clone.legCounts); System.out.println("原來普通狗的腿數:" + clone.dog); DogClone clone1 = (DogClone)clone.clone(); clone1.legCounts = 2; Dog dog = clone1.dog; dog.changeLegCounts(); System.out.println("克隆後原來的克隆狗腿數:" + clone.legCounts); System.out.println("克隆後原來的普通狗腿數:" + clone.dog); System.out.println("克隆後的克隆狗腿數:" + clone1.legCounts); System.out.println("克隆後的普通狗腿數:" + clone1.dog); } }
優勢:能夠動態添加產品,並不會影響到總體的結構java
缺點:每一個原型類都須要配備一個克隆方法,這須要在設計初期就要通盤考慮清楚,由於若是在已有的類基礎上再去添加克隆方法是比較困難的。另外就是若是須要實現深層次複製時,須要編寫必定量的代碼ide