Java design Pattern GOF23 04 prototype mode

Source: Internet
Author: User
Tags getdate

I. Introduction to PROTOTYPE mode

Because new objects in Java require more resources than a clone object, it is generally necessary to

The process of creating a large number of objects in a short period of time and the new object consumes more resources using prototype mode.

To clone a class that requires this class to implement the Cloneable interface, overload the Clone method, which is on the bottom

The Clone object is implemented through a memory copy and is therefore highly efficient.

 PackageCom.lz.prototype;Importjava.util.Date; Public classShallowcloneImplementscloneable{PrivateString name; Private intAge ; PrivateDate date;  PublicShallowclone () {} PublicShallowclone (String name,intAge , date date) {        Super();  This. Name =name;  This. Age =Age ;  This. Date =date; }         PublicString GetName () {returnname; }     Public voidsetName (String name) { This. Name =name; }     Public intGetage () {returnAge ; }     Public voidSetage (intAge ) {         This. Age =Age ; }     PublicDate getDate () {returndate; }     Public voidsetDate (date date) { This. Date =date; } @OverrideprotectedObject Clone ()throwsclonenotsupportedexception {Object obj=Super. Clone (); returnobj; }}
 PackageCom.lz.prototype;Importjava.util.Date; Public classShallowtest { Public Static voidMain (string[] args) {Shallowclone SC1=NewShallowclone ("Laro", 20,NewDate ());        System.out.println (SC1);        System.out.println (Sc1.getname ());        System.out.println (Sc1.getage ());        System.out.println (Sc1.getdate ()); Shallowclone SC2=NULL; Try{SC2=(Shallowclone) Sc1.clone (); } Catch(clonenotsupportedexception e) {e.printstacktrace (); } sc1.setdate (NewDate ());        System.out.println (SC2);        System.out.println (Sc2.getname ());        System.out.println (Sc2.getage ());    System.out.println (Sc2.getdate ()); }}

Two. Prototype mode efficiency detection

The following is a simple efficiency test

 PackageCom.lz.prototype; Public classEfficiency { Public Static voidMain (string[] args)throwsclonenotsupportedexception {test01 (); T s=NewT ();    test02 (s); }         Public Static voidtest01 () {LongStart =System.currenttimemillis ();  for(inti=0; i<1000; i++) {T s=NewT (); }        LongEnd =System.currenttimemillis (); System.out.println (End-start) + "MS"); }         Public Static voidtest02 (T s)throwsclonenotsupportedexception {LongStart =System.currenttimemillis ();  for(inti=0; i<1000; i++) {T copy=(T) S.clone (); }        LongEnd =System.currenttimemillis (); System.out.println (End-start) + "MS"); }}classTImplementscloneable{ PublicT () {Try{Thread.Sleep (1); } Catch(interruptedexception e) {e.printstacktrace (); }} @OverrideprotectedObject Clone ()throwsclonenotsupportedexception {return Super. Clone (); }}

Three. Shallow copy and deep copy

The following is a simple code implementation of course the above code only implements a shallow copy, the meaning of a shallow copy is only the clone of the object itself, and this class contains other reference objects are not

Implement clone. This is where you need to change the code to implement a deep copy

 PackageCom.lz.prototype;Importjava.util.Date; Public classDeepcloneImplementscloneable{PrivateString name; Private intAge ; PrivateDate date;  PublicDeepclone () {} PublicDeepclone (String name,intAge , date date) {        Super();  This. Name =name;  This. Age =Age ;  This. Date =date; }         PublicString GetName () {returnname; }     Public voidsetName (String name) { This. Name =name; }     Public intGetage () {returnAge ; }     Public voidSetage (intAge ) {         This. Age =Age ; }     PublicDate getDate () {returndate; }     Public voidsetDate (date date) { This. Date =date; }    /** Achieve deep copy * @see Java.lang.object#clone ()*/@OverrideprotectedObject Clone ()throwsclonenotsupportedexception {Object obj=Super. Clone (); Deepclone DC=(deepclone) obj; Dc.date= (Date) This. Date.clone (); returnobj; }}

The simple implementation of deep clone is simple enough to clone only the inner reference class of the class that needs to clone.

However, this method is not easy to implement in more complex classes, and it is possible to use serialization and deserialization to implement clone

Of course a class that wants to implement a serialization and deserialization session needs to implement the Serializable interface

The following is a simple code implementation:

 PackageCom.lz.prototype;ImportJava.io.ByteArrayInputStream;ImportJava.io.ByteArrayOutputStream;ImportJava.io.ObjectInputStream;ImportJava.io.ObjectOutputStream;Importjava.io.Serializable;Importjava.util.Date;/** Serialization of deserialized clone objects*/ Public classTest01 { Public Static voidMain (string[] args)throwsException {Sheep S1=NewSheep ("Tom",NewDate (1000000000L)); Bytearrayoutputstream Bos=NewBytearrayoutputstream (); ObjectOutputStream Oos=NewObjectOutputStream (BOS);        Oos.writeobject (S1); byte[] bytes =Bos.tobytearray (); Bytearrayinputstream bis=Newbytearrayinputstream (bytes); ObjectInputStream Ois=NewObjectInputStream (bis); Sheep S2=(Sheep) ois.readobject (); System.out.println ("Before testing");        System.out.println (S1); System.out.println (S1.getname ()+" " +s1.getbirthday ());        SYSTEM.OUT.PRINTLN (S2); System.out.println (S2.getname ()+" " +s2.getbirthday ()); S1.setname ("Laro"); S1.setbirthday (NewDate (1000000000L)); System.out.println ("After testing");        System.out.println (S1); System.out.println (S1.getname ()+" " +s1.getbirthday ());        SYSTEM.OUT.PRINTLN (S2); System.out.println (S2.getname ()+" " +s2.getbirthday ()); }}classSheepImplementscloneable, serializable{PrivateString name; PrivateDate birthday;  PublicSheep () {} PublicSheep (String name, Date birthday) {Super();  This. Name =name;  This. Birthday =birthday; }     PublicString GetName () {returnname; }     Public voidsetName (String name) { This. Name =name; }     PublicDate Getbirthday () {returnbirthday; }     Public voidsetbirthday (Date birthday) { This. Birthday =birthday; } @OverrideprotectedObject Clone ()throwsclonenotsupportedexception {return Super. Clone (); }}

Java design Pattern GOF23 04 prototype mode

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.