06.创建型————原型模式
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); } }
优点:可以动态添加产品,并不会影响到整体的结构
缺点:每个原型类都需要配备一个克隆方法,这需要在设计初期就要通盘考虑清楚,因为如果在已有的类基础上再去添加克隆方法是比较困难的。另外就是如果需要实现深层次复制时,需要编写一定量的代码