原型模式(思惟導圖)

圖1 原型模式【點擊查看大圖】dom

1,原型對象

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);
    }
}

 

2,測試驗證

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();
        }
    }
}

 

3,關於原型模式與單例模式衝突的緣由

首先:單例模式是隻能產生一個實例化對象,構造方法私有化,不能經過普通的方法進行實例化。測試

若是想要獲取新的實例化對象,要怎麼辦呢?spa

  ①直接跳過無視私有化構造:反射機制prototype

  ②我壓根不新創建一個實例化對象,跳過私有化構造,我直接進行開闢新空間的數據深拷貝:原型模式【必須實現Cloneable方法code

  以上兩種方法均可以無視單例模式,獲取多個實例化對象。對象

相關文章
相關標籤/搜索