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)