天天看點

23種設計模式----原型模式

原型模式

通過implements Cloneable接口,該對象可以通過clone實作對象的拷貝.      

1.抽象一個手機類,實作cloneable接口

public abstract class Phone implements Cloneable {
    private String telephone = "";
    public Phone(String telephone) {
        this.telephone = telephone;
    }
    @Override
    protected Phone clone() {
        try {
            return (Phone) super.clone();
        } catch (CloneNotSupportedException e) {
            e.printStackTrace();
            return null;
        }
    }
    public String getTelephone() {
        return telephone;
    }
    public void setTelephone(String telephone) {
        this.telephone = telephone;
    }
}
           

2.華為手機 

public class HuaWeiPhone extends Phone {

    public HuaWeiPhone(String telephone) {
        super(telephone);
    }
}
           

3.測試類 

public class Test {
    public void test() {
        HuaWeiPhone huaWeiPhone1 = new HuaWeiPhone("1323");

        HuaWeiPhone huaWeiPhone2 = (HuaWeiPhone) huaWeiPhone1.clone();

        System.out.println(huaWeiPhone1 == huaWeiPhone2);

        //輸出結果為false,說明并不是傳值引用 ,兩個對象有自己的位址。
    }
}
           

繼續閱讀