Java Design Patterns-prototypes (prototype)

Source: Internet
Author: User

Sometimes it takes a lot of resources to create objects, but there is a lot of repetition between each object. We can choose to clone the other object as a template after creating the good one object, and make a minor modification to use it elsewhere.

You need to implement the Cloneable interface, overriding the Clone () method. is actually called the Clone () method of the object class.

The cloned object simply replicates the data of the original object, each of which is independent and whose memory address is different.

/*** Created by Wangbin10 on 2018/5/18.*/ Public classPrototype2Implementscloneable,serializable {Private Static Final LongSerialversionuid = 2L; PrivateString name; PrivateInteger Payamount; PrivateString msg;  PublicPrototype2 () {} PublicPrototype2 (string name, Integer Payamount, String msg) { This. Name =name;  This. Payamount =Payamount;  This. msg =msg; }     PublicString GetName () {returnname; }     Public voidsetName (String name) { This. Name =name; }     PublicInteger Getpayamount () {returnPayamount; }     Public voidSetpayamount (Integer payamount) { This. Payamount =Payamount; }     PublicString getmsg () {returnmsg; }     Public voidsetmsg (String msg) { This. msg =msg; }     PublicPrototype2 Clone ()throwsclonenotsupportedexception {Prototype2 clone= (Prototype2)Super. Clone (); returnclone; }}

/*** Created by Wangbin10 on 2018/5/18.*/ Public classPTest { Public Static voidMain (string[] args)throwsclonenotsupportedexception {Prototype2 P1=NewPrototype2 ("Zhangsan", "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 Design Patterns-prototypes (prototype)

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

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.