Design mode-prototype mode

Source: Internet
Author: User
Tags requires shallow copy

definition: Use the prototype instance to specify the kind of objects created and create new objects by copying them.

Type: Create class Mode

class Diagram:

The prototype pattern is mainly used for object replication, and its core is the prototype class prototype in the class diagram. The prototype class requires the following two conditions: implementation of the Cloneable interface. In the Java language, there is a cloneable interface, which only works by notifying the virtual machine at runtime that it can safely use the Clone method on classes that implement this interface. In a Java virtual machine, only classes that implement this interface can be copied, or clonenotsupportedexception exceptions will be thrown at run time. Override the Clone method in the object class. In Java, the parent class of all classes is the object class, and the object class has a Clone method that returns a copy of the object, but its scope is protected type, and the generic class cannot be called, so The prototype class needs to modify the scope of the Clone method to the public type.

Prototype mode is a relatively simple mode, it is very easy to understand, implement an interface, rewrite a method to complete the prototype mode. In practical applications, prototype patterns rarely appear alone. Often mixed with other patterns, his prototype class prototype also uses abstract classes instead.

Implementation code:

    Class Prototype implements cloneable {public  
        Prototype clone () {  
            Prototype Prototype = null;  
            try{  
                prototype = (prototype) super.clone ();  
            } catch (Clonenotsupportedexception e) {  
                e.printstacktrace ();  
            }  
            return prototype;   
        }  
    }  
      
    Class Concreteprototype extends prototype{public  
        Void Show () {  
            System.out.println ("prototype Pattern implementation class");  
        }  
    } Public  
      
    class Client {public  
        static void Main (string[] args) {  
            concreteprototype cp = new Concreteprototyp E ();  
            for (int i=0; i<; i++) {  
                Concreteprototype CLONECP = (concreteprototype) cp.clone ();  
                Clonecp.show ();}}}  
      

the advantages and application scenarios of prototype mode

Creating an object using the prototype schema is much better performance than a direct new object, because the Clone method of the object class is a local method that directly operates in-memory binary streams, especially when copying large objects, where performance is significantly different.

Another benefit of using prototype mode is simplifying the creation of objects, making it as simple as copying and pasting as we edit the document.

Because of these advantages, you can consider using the prototype pattern when you need to create similar objects repeatedly. For example, to create objects in a loop, if the object creation process is complex or a lot of cycles, using prototype mode can not only simplify the creation process, but also can improve the overall performance of the system.

Considerations for prototyping patterns copying an object using prototype mode does not invoke the constructor of the class. Because object replication is done by invoking the Clone method of the object class, it replicates the data directly in memory and therefore does not invoke the constructor of the class. Not only does the code in the construction method not execute, but even access permissions are not valid for the prototype mode. Do you remember the singleton pattern? In singleton mode, a singleton can be implemented as long as the access permission of the construction method is set to private type. However, the Clone method directly ignores the permissions of the constructor method, so the singleton mode is conflicting with the prototype mode and should be paid special attention when used. Deep copy with light copy. The Clone method of the object class copies only the basic data types in the object, and is not copied for arrays, container objects, reference objects, and so on, which is a shallow copy. If you want to implement a deep copy, you must copy the array, container object, reference object, and so on in the prototype schema separately. For example:

    public class Prototype implements cloneable {  
        private ArrayList list = new ArrayList ();  
        Public Prototype Clone () {  
            Prototype Prototype = null;  
            try{  
                prototype = (prototype) super.clone ();  
                Prototype.list = (ArrayList) this.list.clone ();  
            } catch (Clonenotsupportedexception e) {  
                e.printstacktrace ();  
            }  
            return prototype;   
        }  
    }  

Since ArrayList is not a basic type, the member variable list, which is not copied, requires that we implement a deep copy ourselves, fortunately, most of the container classes provided by Java implement the Cloneable interface. So it's not particularly difficult to make deep copies.

PS: Deep copy and shallow copy problem, deep copy has 8 basic types in Java and their package type, plus string type. The rest are shallow copies.


Reproduced from: Design mode-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.