Design Pattern (6) prototype Pattern

Source: Internet
Author: User
Tags class manager

Design Pattern (6) prototype Pattern

1. Let's talk about Naruto's shadows

The Naruto stole the scroll and learned the banned technique: Shadow separation. When Naruto uses the shadow separation technique, many people will appear exactly the same as Naruto, just as copied, this film separation technique is called prototype in the field of object-oriented design.

Ii. What is prototype

With the above example of Naruto, it is easier to understand the definition of circular pattern. The definition of GOF is as follows: use a prototype instance to specify the type of the object to be created and create a new object by copying these prototype objects.

The clone () method is provided in Java to clone objects. Therefore, Prototype implementation is much simpler.

Iii. Let's talk about the clone () method.

All Java classes are inherited from the java. lang. Object class, and the Object class provides the following method to copy objects:

protected Object clone()

Subclass can also overwrite this method and use its own logic to implement its own replication method. All classes that can use the clone () method must implement the Cloneable interface. The Cloneable interface only serves to notify the Java Virtual Machine to safely use the clone method in this class during runtime.

There are two types of cloning: shallow cloning and deep cloning.

Shortest clone:

 

As shown in, simple replication only copies the object value. We know that there are two types of object attributes: basic type and reference type, for data of the basic type of replication, a copy is copied to the new object. For the attribute of the reference type, only the referenced value is copied. The specific object to which the reference is directed will not be copied, therefore, A and B are actually using the same object c. If A changes the attribute of c in A, B can also see it, because the change is A common object between the two. The clone method provided by Java is of this type.

 

The difference between deep replication and light replication is that deep replication not only copies object references, but also copies objects referenced by references. Therefore, in the second figure, A and B point to different objects. Operations on c objects in A do not affect B.

Cloning conditions:
1. For any object x, there are: x. clone ()! = X. In other words, the cloned object is not the same as the original object.
2. For any object x, x. clone (). getClass = x. getClass (). In other words, the cloned object is of the same type as the original object.
3. If the equals () method of object x is properly defined, x. clone (). equals (x) should be true.

Description of the equals method:The cloned objects are divided into variable objects and immutable Objects Based on their internal states (the internal values of String cannot be changed ). For mutable objects, true is returned only when they are the same object. For unchanged objects, true is returned when their internal state values are the same, however, the internal status is not necessarily the same object.

Iv. Structure of the prototype model

There are two prototype modes: one is a prototype without management classes and the other is a prototype with management classes.

The following is a prototype without a management class:

 

This form involves three roles:

Customer role: the customer requests to create an object.

Abstract prototype role: This is an abstract role, which is usually implemented by a Java interface or a Java Abstract class. This class may inherit the Cloneable interface.

Prototype role: the Copied object. This role must implement the interfaces required by the abstract prototype role.

Let's take a look at the specific use process through an instance.

Let's take a common example in a university. If you have a senior in a class, you don't have to worry about the homework of the entire class. You can copy the homework of the Senior.

This class is the abstract parent class of a job. It defines methods to be implemented for some jobs. Here, only one mathematical job class is implemented, and programming jobs will be available in the future.

package com.designpattern.prototype1;public abstract class Homework implements Cloneable {    public abstract Object clone();    public abstract void show();}

The class of a mathematical job must implement its own replication logic, because the method of copying a mathematical job and a programming job is definitely different.

Package com. designpattern. prototype1; import java. util. date; public class MathHomework extends Homework {/*** here, only A Date class is used to represent the deep copy */private Date a = new Date (); private int A = 1; public void show () {System. out. println ("Math clone");}/*** implement your own cloning method */public Object clone () {MathHomework m = null; /*** deep copy */m = (MathHomework) this. clone (); m. A = (Date) this. getA (). clone (); return m;} public Date getA () {return ;}}

The client can use xueba's homework for plagiarism.

Package com. designpattern. prototype1; public class Main {public static void main (String [] args, the homework of the class depends on him */MathHomework xueba = new MathHomework ();/*** the scum is copied from xueba */MathHomework xuezha = (MathHomework) xueba. clone (); xuezha. show ();}}

If there are two school masters in A class, some of the students in the class will be more than A, and some will copy B's. In this case, the system must keep two prototype classes, at this time, it is more convenient to use our prototype with management class.

The structure is as follows:

Newly Added management class:

Package com. designpattern. prototype1; import java. util. map; public class Manager {private static Manager manager; private Map prototypes = null; private Manager () {manager = new Manager ();} // use the simple factory mode public static Manager getManager () {if (manager = null) manager = new Manager (); return manager;} public void put (String name, homework prototype) {manager. put (name, prototype);} public Homework getPrototype (String name) {if (prototypes. containsKey (name) {return (Homework) prototypes. get (name )). clone ();} else {Homework homework = null; try {homework = (Homework) Class. forName (name ). newInstance (); put (name, homework);} catch (Exception e) {e. printStackTrace () ;}return homework ;}}}
Package com. designpattern. prototype1; public class MainManager {public static void main (String [] args) {/*** create a student master, the class's homework depends on him */MathHomework xueba = new MathHomework (); Manager. getManager (). put ("com. designpattern. prototype1.MathHomework ", xueba);/*** the dregs are all copied from xueba */MathHomework xuezha = (MathHomework) Manager. getManager (). getPrototype ("com. designpattern. prototype1.MathHomework "); xuezha. show ();}}

The prototype of the simple form and registration form have their own strengths and weaknesses. If the number of prototype objects to be created is small and relatively fixed, a simple form can be used, if the number of created prototype objects is not fixed, the second method is recommended.

V. Advantages and Disadvantages of Prototype

Advantages:
1. encapsulate the product creation process. The client does not need to understand the specific creation process of the product.
2. Using the Java clone method to create an object is certainly much faster than using new to create an object, especially when it is very complex.
3. You can add a new product without modifying other code, which complies with the "On-Off" principle.
Disadvantages:The biggest drawback of the prototype mode is that each class must have a clone method. If the composition of this class is not complex, it is better. If the composition of the class is complex, it is very difficult to implement deep replication.

Vi. prototype mode selection

Assume that the product category of a system is dynamically loaded, and the product category has a certain hierarchical structure. In this case, if the factory model is used, the factory class has to have a corresponding level structure. Once the hierarchical structure of the product class changes, the hierarchical structure of the factory class has to be changed accordingly. this is inconvenient for systems with frequent changes in the product structure to adopt the factory model. In this case, if the prototype mode is used, a clone method can be assembled for each product class to avoid the use of factory classes with a fixed level structure.

Related Article

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.