Java programmer from stupid bird to cainiao () big talk design pattern (5) creator pattern and prototype Pattern

Source: Internet
Author: User

This article is from: Cao shenghuan blog column. Reprinted please indicate the source:Http://blog.csdn.net/csh624366188 

 

The Creator mode is the most responsible design mode in the Creation Mode. The Creator is responsible for building each part of an object and completing the assembly process. the build mode is mainly used for complex product production, separating Component Construction Details to achieve good scalability. The logic of the constructed object instance is moved outside the class, and the construction logic of this class is defined outside the class. It separates the construction process of a complex object from the object representation. The direct effect is to simplify a complex object into a relatively simple object. It emphasizes the product construction process.

In a software system, sometimes it is faced with the creation of "a complex object", which is usually composed of sub-objects of each part using a certain algorithm; due to changes in requirements, the various parts of this complex object often face drastic changes, but the algorithms that combine them are relatively stable. How to deal with this change? How can we provide a "encapsulation mechanism" to isolate the changes of "various parts of complex objects", so as to keep the "stable Construction Algorithm" in the system from changing with demand? This is the builder mode.

Intent:Separates the construction of a complex object from its representation, so that different representations can be created during the same construction process.

Class diagram:

Abstract builder ):An abstract interface is provided to standardize the construction of each component of a product object. This interface specifies which parts of a complex object should be created, and does not involve the creation of specific object parts.
Specific Builder (concrete builder ):Implement the builder interface to create different parts of complex objects based on different business logic. After the construction process is complete, provide the product instance.
Ctor ):Call a specific builder to create various parts of a complex object. The instructor does not involve the information of a specific product. He is only responsible for ensuring that all parts of the object are completely created or created in a certain order.
Product ):The complex object to be created.

Applicability:

1. The product objects to be generated have a complex internal structure.

2. The properties of the product objects to be generated depend on each other. The Builder mode can force the order of generation.

3. Some other objects in the system will be used during object creation. These objects are not easy to obtain during product object creation.

Effect:

1. The internal representation of the product can be changed independently when the builder mode is used. By using the builder mode, the client does not have to know the details of the product composition.

2. Each builder is relatively independent of other builders.

3. The final product built by the model is easy to control.

Next, let's take a look at an implementation form of the classic creator mode, and then propose several improvement solutions for this classic mode, the clothing process described above is used as an example to illustrate the principles and ideas of the Creator mode. I hope that you can flexibly apply the process to actual projects. Achieve the purpose of learning to use.

Let's take a look at the specific code implementation:

Package builder; public class product {arraylist <string> parts = new arraylist <string> (); Public void add (string part) {parts. add (part);} public void show () {system. out. println ("product creation ------------"); For (string part: parts) {system. out. println (Part) ;}} public abstract class builder {public abstract void buildparta (); public abstract void buildpartb (); public abstract product getresult ();} public class concretebuilder1 extends builder {private product Product = new product (); @ overridepublic void buildparta () {product. add ("Part A") ;}@ overridepublic void buildpartb () {product. add ("Part B") ;}@ overridepublic product getresult () {return product ;}} public class concretebuilder2 extends builder {private product Product = new product (); @ overridepublic void buildparta () {product. add ("Part X") ;}@ overridepublic void buildpartb () {product. add ("part y") ;}@ overridepublic product getresult () {return product ;}} public class director {public void construct (Builder) {builder. buildparta (); builder. buildpartb () ;}} public class testbuilder {public static void main (string [] ARGs) {Director ctor = new director (); builder b1 = new concretebuilder1 (); builder b2 = new concretebuilder2 (); Director. construct (B1); product p1 = b1.getresult (); p1.show (); Director. construct (B2); product P2 = b2.getresult (); p2.show ();}}

Through the above Code, we provide the core code form of the classic creator mode, so there are undoubtedly the following disadvantages for the above:

1. The ibuilder interface must define a complete assembly process. Once defined, it cannot be modified dynamically.

2. There is a certain dependency between builder and specific objects. Of course, flexibility can be achieved through decoupling through interfaces.

3. the builder must know the specific process.

How can we solve the above problems? I think the previous creation mode has given me enough experience to provide flexibility through configuration files or other forms.

Prototype

Use a prototype instance to specify the type of the object to be created, and copy the prototype to create a new object. The prototype mode is a creation design mode. The prototype mode allows an object to create another custom object. You do not need to know how to create any details. The working principle is: by passing a prototype object to the object to be created, the object to be created is created by requesting the prototype object to copy them. It mainly faces the following problems: the creation of "some objects with complex structures"; these objects are often subject to drastic changes due to changes in requirements, however, they have stable and consistent interfaces.

The biggest feature of the prototype mode is to clone an existing object, which has two results,One is light replication, and the other is deep replication.Here, we will also discuss the principles of deep replication and shallow replication, which may make it easier for you to understand the usage of this prototype. We all know that the creation mode is generally used to create a new object, and then we use this object to complete some object operations, in the prototype mode, we can quickly create an object without providing special new () operations. This is undoubtedly a very effective method, quickly create a new object.

Schematic diagram of the prototype mode:

The main idea of prototype mode isClone a new object based on the existing objectGenerally, a clone method is provided inside an object to return a copy of the object. In this way, the object is created, compared to the several types of creation modes we mentioned earlier, the factory mode and abstract factory mentioned earlier are the process of encapsulating specific new operations through the factory, return a new object. Sometimes it is not worthwhile to create an object through the factory. Especially in the following scenarios, the prototype mode may be simpler and more efficient.

Main application scenarios:

1. If our object type is not determined at the beginning, but determined at runtime, it is easier to clone a New Type through this type of object.

2. Sometimes we may need a copy of an object in a certain state in the actual project. This premise is very important. How can we understand this, for example, sometimes we need to compare the status of an object after processing and whether the status before processing has changed. Maybe we need to execute a segment before processing, clone the copy of the object state at this time, and then wait for the execution status to compare accordingly. Such applications often appear in projects.

3. When we are dealing with some objects that are relatively simple and have little difference between objects, there may be several fixed attributes that are different, we may be more appropriate to use the prototype mode.

Deep replication and light replication:

(1) shallow copy (shallow clone)
All variables of the Copied object contain the same value as the original object, and all references to other objects still point to the original object. In other words, the shortest copy only copies the objects to be considered, rather than the objects referenced by the shortest copy.
(2) Deep replication (deep cloning)
All variables of the Copied object contain the same value as the original object, except those variables that reference other objects. Variables that reference other objects will point to new objects that have been copied, instead of the original referenced objects. In other words, deep replication copies all the objects referenced by the objects to be copied.

The following example shows how to implement the following prototype:

Import Java. io. bytearrayinputstream; import Java. io. bytearrayoutputstream; import Java. io. ioexception; import Java. io. objectinputstream; import Java. io. objectoutputstream; import Java. io. serializable; Class prototype implements cloneable, serializable {private string STR; private temp; public object clone () throws clonenotsupportedexception {// light clone prototype = (prototype) super. clone (); Return prototype;} public object deepclone () throws ioexception, classnotfoundexception {// deep clone into BO = new bytearrayoutputstream (); objectoutputstream oo = new objectoutputstream (BO ); oo. writeobject (this); bytearrayinputstream Bi = new bytearrayinputstream (BO. tobytearray (); objectinputstream OI = new objectinputstream (BI); return Oi. readobject ();} Public String getstr () {return STR;} public void setstr (string Str) {This. STR = STR;} public temp gettemp () {return temp;} public void settemp (temp) {This. temp = temp;} class temp implements serializable {} public class test {public static void main (string [] ARGs) throws clonenotsupportedexception, classnotfoundexception, ioexception {prototype Pt = new prototype (); temp = new temp (); PT. settemp (temp); PT. setstr ("Hello World"); system. out. println ("creating objects using the shortest clone method"); prototype pt1 = (prototype) pt. clone (); system. out. println ("============================="); system. out. println ("compare the STR values of Pt and pt1:"); system. out. println (pt. getstr (); system. out. println (pt1.getstr (); system. out. println ("after modifying the str value in the pt1 object, compare the STR values of Pt and pt1:"); pt1.setstr ("Hello, world"); system. out. println (pt. getstr (); system. out. println (pt1.getstr (); system. out. println ("==========================="); system. out. println ("compare the temp object values in PT and pt1"); system. out. println (pt. gettemp (); system. out. println (pt1.gettemp (); system. out. println ("using the deep clone method to create objects"); system. out. println ("========================"); pt1 = (prototype) PT. deepclone (); system. out. println (pt. gettemp (); system. out. println (pt1.gettemp ());}}

Output result:
Create an object using the shortest cloning method
==================================
Compare the STR values of Pt and pt1:
Hello World
Hello World
After modifying the str value in the pt1 object, compare the STR values of Pt and pt1:
Hello World
Hello, world
======================================
Compare the values of temp objects in PT and pt1
Temp @ affc70
Temp @ affc70
Create an object using the deep clone method
======================================
Temp @ affc70
Temp @ 15d56d5

From the output, we can see that object is used. the clone () method can only be cloned at a shortest level, that is, only objects whose member variables are of the basic or string type can be cloned, to clone a member variable of the class type object, use the serialization of the object. Otherwise, the cloned prototype object will share the same temp instance.

Summary:

The prototype mode is the most special mode in the creation mode. The specific creation process is provided by the object itself. In this way, in many scenarios, we can easily and quickly build new

Objects, as described in the previous analysis, we may use object cloning to achieve better results than other creation modes, the cost is much lower. For example,

The prototype can seamlessly scale the system. Why? For example, if another created factory adds an object type

Without a doubt, we all need to modify the form of code. This is undoubtedly dangerous for common public applications, so through the prototype mode, you can solve this problem.

Because the type itself can implement this method, but it also has some shortcomings. Every object implements this method, which is undoubtedly a huge workload, however, in some special environments

In the project, the prototype mode may be a good choice.

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.