Prototype mode of creator mode

Source: Internet
Author: User

Prototype mode: Prototype prototype mode is a creation design pattern, prototype mode allows an object to create another customizable object without knowing the details of how to create it, by passing a prototype object to the object to be created, The objects to be created are created by requesting the prototype object to copy them themselves.

In fact, it is through a copy of the original object, as a new object, change some properties of the original object, the process of obtaining a new object, the principle is to use the Clone method in Java (C # There is also a clone method, other languages do not understand. C + + should be a memory copy bar).

Look at the following section of code:

Declares a ship class as a class that we can Colne, thus inheriting the Cloneable interface. The code is as follows:

Importjava.io.Serializable;Importjava.util.Date; Public classShipImplementscloneable, Serializable { PublicString name;  PublicString GetName () {returnname; }     Public voidsetName (String name) { This. Name =name; }    PrivateDate BirthDay;  PublicDate Getbirthday () {returnBirthDay; }     Public voidSetbirthday (Date birthDay) { This. BirthDay =BirthDay; }     PublicObject Clone ()throwsclonenotsupportedexception {Object o=Super. Clone (); returno; }         PublicShip (String name, Date birthDay) {Super();  This. Name =name;  This. BirthDay =BirthDay; }}

Then take a look at how to invoke it in a class:

Importjava.util.Date; Public classMain { Public Static voidMain (string[] args)throwsclonenotsupportedexception {Date Date=NewDate (123445543L); Ship S1=NewShip ("Dorian", date);        System.out.println (S1); System.out.println (S1.getname ()+ ":" +s1.getbirthday ()); Date.settime (234243234L); Ship S2=(ship) s1.clone (); S2.setname ("The Son of Dorian.");        SYSTEM.OUT.PRINTLN (S2); System.out.println (S2.getname ()+ ":" +s2.getbirthday ()); }}

The result of this execution is

18:17:25 CST 197001:04:03 CST 1970

The description is not a class anymore, but the parameters inside are the same (except for your own modifications), so that you can quickly get a new object instead of using the new method.

But here is the problem, shallow copy and deep copy problem, here is a shallow copy, that is, S1 and S2 use a Date object, they copy, copy the reference, point to the same address. If the call changes to this:

1  Public Static voidMain (string[] args)throwsclonenotsupportedexception {2Date Date =NewDate (123445543L);3ship S1 =NewShip ("Dorian", date);4Ship S2 =(ship) s1.clone ();5         6Date.settime (234243234L);7 System.out.println (S1);8System.out.println (S1.getname () + ":" +s1.getbirthday ());9         TenS2.setname ("The Son of Dorian"); One System.out.println (S2); ASystem.out.println (S2.getname () + ":" +s2.getbirthday ()); -}

The output is this:

1 prototype mode [email protected]  2 Dolly: Sun Jan 01:04:03 CST 19703 prototype mode [email protected]4 Billy's son: Sun Jan 01:04:03 CST 1970

These two calls make it clear that this is a shallow copy. Let's see how the deep copy is done.

1  PublicObject Clone ()throwsclonenotsupportedexception {2Object o =Super. Clone ();3         4         //Add the following code for deep clone5ship S =(ship) o;6S.setbirthday ((Date) This. Birthday.clone ());//clone the attribute as well! 7         8         returno;9}

Change the Clone method, add two lines of code, and then look at the results

1 prototype mode [email protected]  2 Dolly: Sun Jan 01:04:03 CST 19703 prototype mode [email protected]4 Billy's son: Fri Jan 18:17:25 CST 1970

The two times have been different, stating that when the time is set for S1, there is no change to the date object of S2, that is, the date of S2 and S1 is pointing to a different content. This enables a deep copy.

In fact, the method of deep copy can also be implemented using serialization, in order to let our class (ship Class) can be serialized, must inherit the serializable interface. Let's take a look.

1  Public classMain2 {2      Public Static voidMain (string[] args)throwsclonenotsupportedexception, IOException, classnotfoundexception {3Date Date =NewDate (123445543L);4ship S1 =NewShip ("Dorian", date);5                 6Bytearrayoutputstream BOS =NewBytearrayoutputstream ();7ObjectOutputStream Oos =NewObjectOutputStream (BOS);8 Oos.writeobject (S1);9         byte[] bytes =Bos.tobytearray ();Ten          OneBytearrayinputstream bis =Newbytearrayinputstream (bytes); AObjectInputStream Ois =NewObjectInputStream (bis); -              -Ship S2 =(ship) ois.readobject (); the          -Date.settime (234243234L); - System.out.println (S1); -System.out.println (S1.getname () + ":" +s1.getbirthday ()); +          -S2.setname ("The Son of Dorian"); + System.out.println (S2); ASystem.out.println (S2.getname () + ":" +s2.getbirthday ()); at     } -}

The above code uses serialization to save the S1 object in a byte array, and then deserializes the data of the byte array to get the object assigned to S2. After changing the S1 time, the time of S2 has not changed, indicating that this is a deep copy process.

Finally, what is the meaning of the prototype model? In fact, in order to solve the constructor is very complex, the construction takes a long time, we can use the prototype mode to save a lot of time. If we set a sleep (10) in the constructor of a class, construct 1000 times (indicating that the constructor is very complex). By using the generic new and our prototype pattern to produce a newer object for comparison, we will find that the prototype pattern is very fast, and the general new is very slow.

In addition, in spring, there are only two methods of constructor, one is singleton and one is prototype mode. In Factory mode, instead of using new to produce objects (singleton or new), it is faster to build objects in prototype mode.

Prototype mode of creator 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.