設計模式23篇:原型模式

定義:

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

類圖:

這裏寫圖片描述
原型模式淺拷貝:

public class Prototype implements Cloneable {
    public Prototype clone() {
        Prototype prototype = null;
        try {
            prototype = (Prototype) super.clone();
        } catch (CloneNotSupportedException e) {
            // TODO: handle exception
            e.printStackTrace();
        }
        return prototype;
    }
}
public class ConcretePrototype extends Prototype {
    public void show() {
        System.out.println("原型模式實現類");
    }
}
public class Client {

    public static void main(String[] args) {
        // TODO Auto-generated method stub
        ConcretePrototype cp = new ConcretePrototype();
        for (int i = 0; i < 10; i++) {
            ConcretePrototype clonecp = (ConcretePrototype)cp.clone();
            clonecp.show();
        }
    }
}

原型模式深拷貝:

public class Person implements Cloneable{
    public String _mname;

    public Person() {
        _mname = "Nick";
    }
    public Person clone() {
        Person _mPerson = null;
        try {
            _mPerson = (Person) super.clone();
            // prototype._mList = this._mList;
        } catch (CloneNotSupportedException e) {
            // TODO: handle exception
            e.printStackTrace();
        }
        return _mPerson;
    }
}
public class Prototype implements Cloneable {
    Person _mPerson = new Person();
    public Prototype clone() {
        Prototype prototype = null;
        try {
            prototype = (Prototype) super.clone();
            prototype._mPerson = (Person)this._mPerson.clone();
        } catch (CloneNotSupportedException e) {
            // TODO: handle exception
            e.printStackTrace();
        }
        return prototype;
    }
}
public class Client {

    public static void main(String[] args) {
        // TODO Auto-generated method stub
        ConcretePrototype cp = new ConcretePrototype();
        for (int i = 0; i < 10; i++) {
            ConcretePrototype clonecp = (ConcretePrototype)cp.clone();
            clonecp.show();
            System.out.println(clonecp._mPerson._mname);
        }
    }
}

注意:

使用原型模式複製對象不會調用類的構造方法。因爲對象的複製是通過調用Object類的clone方法來完成的,它直接在內存中複製數據,因此不會調用到類的構造方法,和所有的方法,只clone基本數據類型。

發佈了34 篇原創文章 · 獲贊 9 · 訪問量 7萬+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章