Java prototyping mode

Source: Internet
Author: User

The prototype mode belongs to the creation mode of the object. By giving a prototype object to indicate the type of all objects created, and then creating more objects of the same type with the method of copying the prototype object. This is the purpose of the model selection.

Structure of the prototype pattern

The prototype pattern requires that an object implement an interface that can "clone" itself, so that a new instance can be created by copying an instance object itself. Thus, by creating a new object from the prototype instance, it is no longer necessary to care about the type of the instance itself, so long as the method of cloning itself is implemented, it is possible to acquire new objects through this method without having to create them through new.

The prototype pattern has two forms: (1) The Simple form, (2) The registration form, these two forms of expression are only the different realization of the prototype pattern.

Prototype mode in simple form

This is a form that involves three roles:

(1) Customer (client) role: The Customer class presents a request to create an object.

(2) abstract prototype (Prototype) role: This is an abstract role, usually implemented by a Java interface or Java abstract class. This role gives the interfaces required for all the specific prototype classes.

(3) Specific prototype (concrete Prototype) Role: the object being copied. This role needs to implement the interfaces required by the abstract prototype role.

Two forms of comparison

The prototype pattern of simple form and registration form has its merits and shortcomings.

If you need to create a small number of prototype objects and are relatively fixed, you can take the first form. In this case, the reference to the prototype object can be saved by the client itself.

If the number of prototype objects you want to create is not fixed, you can take a second form. In this case, the client does not save a reference to the prototype object, and the task is given to the Administrator object. Before copying a prototype object, the client can see if the Administrator object already has a prototype object that meets the requirements. If so, the object reference can be obtained directly from the Administrator class, and if not, the client needs to replicate the prototype object on its own.

Cloning methods in Java

All classes in Java are inherited from the Java.lang.Object class, and the object class provides a copy of the objects from the protected object Clone () method, which can, of course, displace the method, providing a copy method that satisfies its needs. The basic problem with object replication is that objects typically have references to other objects. When you use the Clone () method of the object class to copy an object, this object's references to other objects are also copied

The Cloneable interface provided by the Java language serves only one function, which is to inform the Java Virtual machine at runtime that it can safely use the Clone () method on this class. You can get a copy of an object by calling this clone () method. Because the object class itself does not implement the Cloneable interface, calling the Clone () method throws a Clonenotsupportedexception exception if the class being considered does not implement the Cloneable interface.

Conditions for cloning to meet

The Clone () method copies a copy of the object and returns it to the caller. The meaning of the so-called "copy" and how the Clone () method is implemented. Generally, the clone () method satisfies the following description:

(1) For any object x, there are: X.clone ()!=x. In other words, a cloned object is not the same object as the original object.

(2) For any object x, there are: X.clone (). GetClass () = = X.getclass (), in other words, the cloned object is the same as the type of the original object.

(3) if the Equals () method of Object x defines its proper words, then x.clone (). Equals (x) should be established.

In the Java language API, all classes that provide the clone () method satisfy these conditions. The Java language designer should also abide by three conditions when designing his own clone () method. In general, the first two of the three conditions above are required, and the third one is optional.

Shallow clones and deep clones

  Whether you are implementing the cloning method yourself or using the cloning method provided by Java, there is a problem of shallow cloning and deep cloning.

    • Superficial cloning

It is only responsible for cloning data passed by value (such as the base data type, string type) without copying the object it refers to, in other words, all references to other objects still point to the original object.

    • Deep cloning

In addition to a shallow clone of the value to be cloned, it is also responsible for cloning the reference type's data. Variables that refer to other objects will point to new objects that have been copied, not those that are already referenced. In other words, a deep clone copies the objects referenced by the object being copied, and this copy of the referenced object is called an indirect copy.

Depth cloning to how many layers, is a difficult to determine the problem. When you decide to copy an object in a deep clone, you must decide whether to take a shallow clone or continue to use deep cloning for objects that are indirectly copied. Therefore, in the case of deep cloning, we need to decide how deep it is to be deep. In addition, in the process of deep cloning, it is very likely that the problem of circular references, must be handled with care.

Using serialization for deep cloning

The process of writing an object into a stream is a serialization (serialization) process, while the process of reading an object from the stream is called a deserialization (deserialization) process. It should be noted that a copy of the object is written to the stream, and the original object still exists inside the JVM.

In the Java language, it is often possible to clone an object in a deep way, so that the object can be implemented serializable interface, then the object (actually a copy of the object) is written into a stream (serialized), and then read back from the stream (deserialized), you can reconstruct the object.

Code:

Package prototype mode; import Java.util.arraylist;import java.util.iterator;import java.util.List; Public classPrones implements cloneable {PrivateString name;  PublicString GetName () {returnname; }     Public voidsetName (String name) { This. Name =name; }     Public intGetage () {returnAge ; }     Public voidSetage (intAge ) {         This. Age =Age ; }     Public intGetsex () {returnsex; }     Public voidSetsex (intsex) {         This. Sex =sex; }     PublicList<string>getfriends () {returnfriends; }     Public voidSetfriends (list<string>friends) {         This. Friends =friends; }    Private intAge ; Private intsex; PrivateList<string>friends;  PublicPrones Clone () {Try{prones prones1=(Prones) Super.clone (); List<String> newfriends =NewArraylist<string>();  for(String friend: This. Getfriends ())            {Newfriends.add (friend);            } prones1.setfriends (Newfriends); returnprones1; } Catch(Exception e) {e.printstacktrace (); return NULL; }    }}
Package prototype mode; import Java.util.arraylist;import java.util.List; Public classText { Public Static voidMain (string[] args) {prones Prones0=NewPrones (); List<String> Frades =NewArraylist<string>(); Frades.add ("1"); Frades.add ("2");        Prones0.setfriends (Frades); Prones Pronesa=Prones0.clone (); System. out. println ("1:"+prones0.getfriends ()); System. out. println ("2:"+pronesa.getfriends ()); Frades.add ("3"); System. out. println ("1:"+prones0.getfriends ()); System. out. println ("2:"+pronesa.getfriends ()); }}

Results

Java prototyping 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.