圖1 原型模式【點擊查看大圖】dom
public class Prototype implements Cloneable{ public Prototype clone(){ Prototype prototype=null; try{ prototype=(Prototype)super.clone(); }catch (CloneNotSupportedException e){ e.printStackTrace(); } return prototype; } } class ConcretePrototype extends Prototype { private int num= (int) (Math.random()*100); public void show() { System.out.println("原型模式實現類-"+num); } }
public class Client { public static void main(String[] args) { ConcretePrototype cp=new ConcretePrototype(); for(int i=0;i<10;i++){ ConcretePrototype clonecp=(ConcretePrototype) cp.clone(); clonecp.show(); } } }
首先:單例模式是隻能產生一個實例化對象,構造方法私有化,不能經過普通的方法進行實例化。測試
若是想要獲取新的實例化對象,要怎麼辦呢?spa
①直接跳過無視私有化構造:反射機制prototype
②我壓根不新創建一個實例化對象,跳過私有化構造,我直接進行開闢新空間的數據深拷貝:原型模式【必須實現Cloneable方法】code
以上兩種方法均可以無視單例模式,獲取多個實例化對象。對象