設計模式-----原型模式

原型模式

定義:

原型實例指定創建對象的種類,並且通過拷貝這些原型創建新的對象

原型模式通類圖

通用類圖

原型模式的核心就是clone方法,通過對對象的拷貝,實現java的Cloneable接口,並重寫clone接口。

public class PrototypeClass  implements Cloneable{      
    //覆寫父類Object方法     
    @Override     
    public PrototypeClass clone(){             
    PrototypeClass prototypeClass = null;             
    try {                    
        prototypeClass = (PrototypeClass)super.clone();             
        } catch (CloneNotSupportedException e) {                        
        //異常處理             
    }             
    return prototypeClass;     
    } 
}

優點

原型模式是在內存二進制流的拷貝,要比直接new一個對象的性能比較好,特別是要在一個循環體內產生大量的對象時,原型模式可以更好的體現其優點。

使用場景

  • 類初始化需要消耗過多的資源
  • 性能和安全要求的場景
  • 通過new產生一個對象需要頻繁的數據準備或訪問權限
  • 一個對象多個修改者的場景

注意事項

一個實現cloneable接口的對象,在clone時不會調用構造函數,

淺拷貝與深拷貝

public class Thing implements Cloneable{     
//定義一個私有變量     
private ArrayList<String> arrayList = new ArrayList<String>();     
@Override     
public Thing clone(){             
    Thing thing=null;             
    try {                    
        thing = (Thing)super.clone();             
    } catch (CloneNotSupportedException e) {                        
        e.printStackTrace();             
    }             
        return thing;     
    }     
    //設置HashMap的值     
    public void setValue(String value){             
        this.arrayList.add(value);     
    }     
    //取得arrayList的值     
    public ArrayList<String> getValue(){             
        return this.arrayList;     
    } 
}

在clone中,只有java的8中基本基本類型進行拷貝,數組以及對象,只是拷貝指針,因此我們上面對象調用clone方法時,克隆出來的對象使用的是一個arrayList。

public class Thing implements Cloneable{     
//定義一個私有變量     
private ArrayList<String> arrayList = new ArrayList<String>();     
@Override     
public Thing clone(){             
Thing thing=null;             
try {                    
    thing = (Thing)super.clone();                    thing.arrayList =(ArrayList<String>)this.arrayList.clone();             } catch (CloneNotSupportedException e) {                    e.printStackTrace();             
}            
return thing;     
} 
}

上述方法,我們添加了

thing.arrayList =(ArrayList<String>)this.arrayList.clone(); 

進行實現深拷貝

注意事項

原型模式不能與final域進行耦合,否則會報錯。

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章