java設計模式-原型(prototype)

來源:互聯網
上載者:User

標籤:zha   throw   test   out   jin   ===   ted   很多   ati   

有時候建立對象是需要耗費很多資源,但是每個對象之間又有大量的重複。我們可以選擇在建立好一個對象後,以之作為模板複製出其他對象,稍作修改,即可用於其他地方。

 需要實現Cloneable介面,重寫clone()方法。其實就是調用的Object類的clone()方法。

複製對象只是複製了原對象的資料,每個對象還是獨立的,他們的記憶體位址不同。

/** * Created by wangbin10 on 2018/5/18. */public class Prototype2 implements Cloneable,Serializable {    private static final long serialVersionUID = 2L;    private String name;    private Integer payAmount;    private String msg;    public Prototype2() {    }    public Prototype2(String name, Integer payAmount, String msg) {        this.name = name;        this.payAmount = payAmount;        this.msg = msg;    }    public String getName() {        return name;    }    public void setName(String name) {        this.name = name;    }    public Integer getPayAmount() {        return payAmount;    }    public void setPayAmount(Integer payAmount) {        this.payAmount = payAmount;    }    public String getMsg() {        return msg;    }    public void setMsg(String msg) {        this.msg = msg;    }    public Prototype2 clone() throws CloneNotSupportedException {        Prototype2 clone = (Prototype2) super.clone();        return clone;    }}

 

/** * Created by wangbin10 on 2018/5/18. */public class PTest {    public static void main(String[] args) throws CloneNotSupportedException {        Prototype2 p1=new Prototype2("zhangsan",23,"hello!welcome to beijing!");        System.out.println(p1.getName()+p1.getPayAmount()+p1.getMsg());        Prototype2 p2 = p1.clone();        p2.setName("lisi");        p2.setPayAmount(24);        System.out.println(p2.getName()+p2.getPayAmount()+p2.getMsg());        System.out.println("============================");        System.out.println(p1.getName()+p1.getPayAmount()+p1.getMsg());    }}

 

java設計模式-原型(prototype)

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.