The beauty of Java [from cainiao to master Evolution] Design Pattern

Source: Internet
Author: User

Design Patterns)

-- Reusable basics of Object-Oriented Software

Design pattern is a set of summary of code design experiences that are repeatedly used, known to most people, classified and catalogued. The design pattern is used to make code reusable, make it easier for others to understand, and ensure code reliability. There is no doubt that the design model is a win-win solution for others and the system. The design model enables code compilation to be truly engineered. The design model is the foundation of software engineering, just like the building blocks. The rational use of the design pattern in the project can perfectly solve many problems. Each pattern has a corresponding principle in the present, each pattern describes a recurring problem around us and its core solution, which is also the reason for its wide application. This chapterThe beauty of Java [from cainiao to masters] SeriesWe will study this chapter in the form of a combination of theory and practice. We hope that the majority of programmers will learn the design model well and become an excellent software engineer!

If you have any questions during reading, please contact egg in time.

Mailbox: xtfggef@gmail.com Weibo:Http://weibo.com/xtfggef

If any reprint is available, please describe the source:Http://blog.csdn.net/zhangerqing

I. Classification of design patterns

In general, the design model is divided into three categories:

There are five creation modes: Factory method mode, abstract factory mode, Singleton mode, builder mode, and prototype mode.

There are seven structural modes: adapter mode, decorator mode, proxy mode, appearance mode, bridging mode, combination mode, and meta mode.

11 behavior models: rule mode, template method mode, observer mode, iteration sub-mode, responsibility chain mode, command mode, memorandum mode, state mode, visitor mode, intermediary mode, interpreter mode.

There are actually two types: Parallel hair mode and Thread Pool Mode. Use an image to describe it as a whole:

Ii. six principles of the design model

1. Open Close Principle)

The principle of opening/closing is to sayOpen to extension and disable Modification. When the program needs to be expanded, you cannot modify the original code to achieve a hot swapping effect. So in a word, it is easy to maintain and upgrade the program to make it more scalable. To achieve this, we need to use interfaces and abstract classes. We will mention this in the specific design.

2. liskov substitution principle)

Liskov substitution principle LSP is one of the basic principles of object-oriented design. In the Rys replacement principle, subclasses can certainly appear where any base class can appear. LSP is the cornerstone of inheritance reuse. Only when the primary class can replace the base class and the functions of the software unit are not affected can the base class be reused, the category class can also add new behaviors based on the base class. The Li's replacement principle is a supplement to the "open-closed" principle. The key step for implementing the "open-close" principle is abstraction. The inheritance relationship between the base class and sub-classes is the specific implementation of abstraction. Therefore, the Li's replacement principle is the standard for the specific steps to implement abstraction. -- From Baidu encyclopedia

3. Dependence inversion principle)

This is the basis of the open/closed principle. The specific content is: True interface programming, dependent on abstraction and not on specifics.

4. Interface segregation principle)

This principle means that using multiple isolated interfaces is better than using a single interface. We can see from this that the design mode is a software design idea, starting from the large-scale software architecture, for the convenience of upgrading and maintenance. So it appears many times above: reducing dependencies and reducing coupling.

5. Demeter Principle)

What is the principle of least understanding? That is to say, an entity should interact with other entities as little as possible so that the system function modules are relatively independent.

6. Composite Reuse Principle)

The principle is to use synthesis/aggregation as much as possible, rather than inheritance.

Iii. Design Pattern in Java 23

Starting from this section, we will introduce in detail the concepts and application scenarios of 23 Design Patterns in Java, and analyze them based on their characteristics and principles of design patterns.

1. Factory method)

There are three factory method modes:

11. General factory ModelCreate a factory class to create instances for some classes that implement the same interface. First, let's look at the relationship diagram:

Example: (here is an example of sending emails and text messages)

First, create a common interface:

public interface Sender {public void Send();}

Second, create an implementation class:

public class MailSender implements Sender {@Overridepublic void Send() {System.out.println("this is mailsender!");}}
public class SmsSender implements Sender {@Overridepublic void Send() {System.out.println("this is sms sender!");}}

Finally, the factory creation class:

Public class sendfactory {public sender produce (string type) {If ("mail ". equals (type) {return New mailsender ();} else if ("SMS ". equals (type) {return New smssender ();} else {system. out. println ("enter the correct type! "); Return NULL ;}}}

Let's test:

public class FactoryTest {public static void main(String[] args) {SendFactory factory = new SendFactory();Sender sender = factory.produce("sms");sender.Send();}}

Output: This is SMS sender!

22. Multiple factory method ModesIs an improvement on the common factory method mode. In the common factory method mode, if the passed string fails, the object cannot be created correctly, multiple factory method modes provide multiple factory methods to create objects respectively. Relationship diagram:

Modify the above Code and modify the sendfactory class as follows:

public class SendFactory {public Sender produceMail(){return new MailSender();}public Sender produceSms(){return new SmsSender();}}

The test class is as follows:

public class FactoryTest {public static void main(String[] args) {SendFactory factory = new SendFactory();Sender sender = factory.produceMail();sender.Send();}}

Output: This is mailsender!

33. Static factory method modeSet the methods in the preceding factory method mode to static. You can directly call the methods without creating an instance.

public class SendFactory {public static Sender produceMail(){return new MailSender();}public static Sender produceSms(){return new SmsSender();}}
public class FactoryTest {public static void main(String[] args) {Sender sender = SendFactory.produceMail();sender.Send();}}

Output: This is mailsender!

In general, the factory mode is suitable: when a large number of products need to be created and have common interfaces, they can be created through the factory method mode. In the above three modes, if the input string is incorrect, the object cannot be correctly created, and the third mode does not need to instantiate the factory class. Therefore, in most cases, we will choose the third static factory method mode.

2. Abstract Factory)

One problem with the factory method mode is that the creation of the class depends on the factory class. That is to say, if you want to expand the program, you must modify the factory class, which violates the closure principle. Therefore, from the design perspective, how can we solve certain problems? The abstract factory mode is used to create multiple factory classes. Once new functions need to be added, new factory classes can be directly added without modifying the previous code. Because the abstract factory is not very easy to understand, let's take a look at the figure first, and then it is easier to understand with the code.

See the example below:

public interface Sender {public void Send();}

Two implementation classes:

public class MailSender implements Sender {@Overridepublic void Send() {System.out.println("this is mailsender!");}}
public class SmsSender implements Sender {@Overridepublic void Send() {System.out.println("this is sms sender!");}}

Two factory classes:

public class SendMailFactory implements Provider {@Overridepublic Sender produce(){return new MailSender();}}
public class SendSmsFactory implements Provider{@Overridepublic Sender produce() {return new SmsSender();}}

Provide an interface:

public interface Provider {public Sender produce();}

Test class:

public class Test {public static void main(String[] args) {Provider provider = new SendMailFactory();Sender sender = provider.produce();sender.Send();}}

In fact, the advantage of this mode is that if you want to add a function: sending timely information, you only need to create an implementation class to implement the sender interface, and at the same time make a factory class to implement the provider interface, it's okay. You don't need to change the existing code. In this way, the scalability is better!

3. Singleton mode (Singleton)

Singleton is a common design pattern. In Java applications, a singleton object can ensure that only one instance exists in one JVM. This mode has several advantages:

1. Some classes are frequently created. For some large objects, this is a huge system overhead.

2. Saves the new operator, reduces the usage frequency of the system memory, and reduces the GC pressure.

3. Some types, such as the core trading engine of the exchange, control the transaction process. If this type can be created multiple times, the system is completely messy. (For example, if a single army has multiple commanders directing at the same time, it will surely be in a mess.) Therefore, only the singleton mode can ensure that the core Transaction Server can independently control the entire process.

First, we will write a simple Singleton class:

Public class Singleton {/* holds Private Static instances to prevent being referenced. The value here is null to achieve delayed loading */Private Static Singleton instance = NULL;/* private constructor, prevent instantiation */private Singleton () {}/* Static engineering method, create instance */public static Singleton getinstance () {If (instance = NULL) {instance = new Singleton ();} return instance;}/* if the object is used for serialization, the object can be consistent before and after serialization */public object readresolve () {return instance ;}}

This class can meet the basic requirements. However, if we put the class without thread security protection in a multi-threaded environment, the problem will certainly occur. How can we solve it? We will first consider adding the synchronized keyword to the getinstance method, as follows:

public static synchronized Singleton getInstance() {if (instance == null) {instance = new Singleton();}return instance;}

However, the synchronized keyword locks this object. This usage degrades the performance because the object is locked every time getinstance () is called. In fact, you only need to lock the object when creating the object for the first time, and then you do not need it. Therefore, you need to improve this area. Let's change it to the following:

public static Singleton getInstance() {if (instance == null) {synchronized (instance) {if (instance == null) {instance = new Singleton();}}}return instance;}

It seems that the problem mentioned above has been solved. The synchronized keyword is added internally, that is, the lock is not required during the call, only when the instance is null, the lock is required only when the object is created, and the performance is improved. However, in this case, there may still be a problem. Let's take a look at the following situation: Creating an object in a Java instruction and assigning values are performed separately, that is, instance = new Singleton (); the statement is executed in two steps. However, the JVM does not guarantee the order of the two operations. That is to say, the JVM may allocate space for the new Singleton instance, assign it to the instance member directly, and then initialize the singleton instance. This may cause an error. Let's take the two threads A and B as an example:

A> line A and line B enter the first if judgment at the same time.

B> A first enters the synchronized block. Because instance is null, it executes instance = new Singleton ();

C> due to the internal optimization mechanism of JVM, JVM first draws some blank memory allocated to the singleton instance and assigns it to the instance Member (Note that at this time the JVM does not start initializing this instance ), then a leaves the synchronized block.

D> B enters the synchronized block. Because the instance is not null at this time, it immediately leaves the synchronized block and returns the result to the program that calls this method.

E> at this time, line B intends to use the singleton instance, but finds that it is not initialized, so an error occurs.

As a result, errors may occur in programs. In fact, the running process of programs is very complicated. From this point, we can see that programs, especially in multi-threaded environments, are more difficult and challenging. We further optimized the program:

private static class SingletonFactory{                 private static Singleton instance = new Singleton();             }             public static Singleton getInstance(){                 return SingletonFactory.instance;             } 

The actual situation is that the singleton mode uses internal classes to maintain the implementation of Singleton. The internal mechanism of JVM ensures that when a class is loaded, the loading process of this class is mutually exclusive. In this way, when we call getinstance for the first time, JVM can help us ensure that the instance is created only once and the memory assigned to the instance is initialized, in this way, we don't have to worry about the above problems. At the same time, this method only uses the mutex mechanism during the first call, which solves the problem of low performance. In this way, we will summarize a perfect Singleton mode for the moment:

Public class Singleton {/* private constructor to prevent instantiation */private Singleton () {}/* here an internal class is used to maintain the singleton */Private Static class singletonfactory {Private Static Singleton instance = new Singleton ();} /* Get instance */public static Singleton getinstance () {return singletonfactory. instance;}/* if the object is used for serialization, the object can be consistent before and after serialization */public object readresolve () {return getinstance ();}}

In fact, it is not necessarily perfect. If an exception is thrown in the constructor, the instance will never be created and an error will occur. Therefore, there is no perfect thing. We can only choose the implementation method that best suits our application scenarios based on the actual situation. Some people also achieve this: Because we only need to synchronize when creating classes, we only need to separate the creation and getinstance () and separately Add the synchronized keyword for the Creation. This is also possible:

public class SingletonTest {private static SingletonTest instance = null;private SingletonTest() {}private static synchronized void syncInit() {if (instance == null) {instance = new SingletonTest();}}public static SingletonTest getInstance() {if (instance == null) {syncInit();}return instance;}}

Considering the performance, the entire program only needs to create an instance once, so the performance will not be affected.

Supplement: the "shadow instance" method is used to synchronously update the attributes of the singleton object.

public class SingletonTest {private static SingletonTest instance = null;private Vector properties = null;public Vector getProperties() {return properties;}private SingletonTest() {}private static synchronized void syncInit() {if (instance == null) {instance = new SingletonTest();}}public static SingletonTest getInstance() {if (instance == null) {syncInit();}return instance;}public void updateProperties() {SingletonTest shadow = new SingletonTest();properties = shadow.getProperties();}}

The Singleton model tells us:

1. The Singleton mode is easy to understand, but it is still difficult to implement it.

2. the synchronized keyword is used to lock objects. When using synchronized, it must be used in proper places (note the objects and processes that need to be locked, sometimes, the entire object and the entire process do not need to be locked ).

At this point, the singleton mode is basically over. At the end, I suddenly think of another problem, that is, it is feasible to use static methods of classes to achieve the effect of Singleton mode, what is the difference between the two?

First, static classes cannot implement interfaces. (From the class point of view, it is acceptable, but that will damage the static state. Because the interface does not allow static modification, it is non-static even if implemented)

Second, a single instance can be delayed for initialization. Static classes are usually initialized during the first loading. The reason for delayed loading is that some classes are large, so delayed loading helps improve performance.

Once again, a singleton class can be inherited and its method can be overwritten. But the internal methods of static classes are static and cannot be overwritten.

Finally, the singleton class is flexible. After all, the implementation is just a common Java class. As long as the basic requirements of the singleton are met, You can implement other functions as you like, but the static class does not work. From the above summary, we can basically see the differences between the two. However, on the other hand, the singleton mode we finally implemented above is implemented using a static class internally, therefore, there is a great correlation between the two, but we have considered different aspects of the problem. The combination of the two ideas can create perfect solutions, just as hashmap uses arrays and linked lists for implementation. In fact, many things in life are like this, there are always advantages and disadvantages when using different methods to solve the problem. The most perfect method is to combine the advantages of each method to solve the problem best!

4. Builder Mode)

The factory class mode provides the mode for creating a single class, while the builder mode manages various products in a centralized manner to create composite objects, the so-called composite object means that a class has different attributes. In fact, the builder mode is the combination of the abstract factory mode and the final test. Let's take a look at the Code:

As before, a sender interface has two implementation classes: mailsender and smssender. Finally, the builder class is as follows:

public class Builder {private List<Sender> list = new ArrayList<Sender>();public void produceMailSender(int count){for(int i=0; i<count; i++){list.add(new MailSender());}}public void produceSmsSender(int count){for(int i=0; i<count; i++){list.add(new SmsSender());}}}

Test class:

public class Test {public static void main(String[] args) {Builder builder = new Builder();builder.produceMailSender(10);}}

From this point, we can see that the builder mode integrates many functions into a class, which can create complicated things. The difference with the engineering mode is that the factory mode focuses on creating a single product, while the builder mode focuses on creating a conforming object and multiple parts. Therefore, whether to select the factory mode or builder mode depends on the actual situation.

5. Prototype)

Although the prototype mode is a creation mode, it has nothing to do with the engineering mode. The concept of this mode is to copy and clone an object as a prototype, generate a new object similar to the original object. This section describes how to copy objects. In Java, the replication object is implemented through clone (). First, create a prototype class:

public class Prototype implements Cloneable {public Object clone() throws CloneNotSupportedException {Prototype proto = (Prototype) super.clone();return proto;}}

It is very simple. A prototype class only needs to implement the cloneable interface and overwrite the clone method. Here, the clone method can be changed to any name, because the cloneable interface is an empty interface, you can define the method name of the implementation class, such as clonea or cloneb, because the focus here is super. clone (), super. clone () calls the object clone () method, while in the object class, clone () is native. In another article, how to implement it, the call to Interpret local methods in Java is not further explored here. Here, I will take a look at the concept of object deep replication in light replication and deep replication. First, we need to understand the concept of object deep replication:

Shallow copy: After copying an object, all the variables of the basic data type are re-created, and the reference type points to the original object.

Deep replication: After an object is copied, it is re-created regardless of the basic data type and reference type. In short, deep replication is completely complete, but not complete.

Here, we will write an example of deep replication:

Public class prototype implements cloneable, serializable {Private Static final long serialversionuid = 1l; private string; private serializableobject OBJ;/* Light copy */public object clone () throws clonenotsupportedexception {prototype proto = (prototype) super. clone (); Return proto;}/* Deep copy */public object deepclone () throws ioexception, classnotfoundexception {/* write the binary stream of the current object */bytearrayoutputstream Bos = new bytearrayoutputstream (); objectoutputstream OOS = new objectoutputstream (BOS); OOS. writeobject (this);/* read the new object generated by binary abortion */bytearrayinputstream Bis = new bytearrayinputstream (Bos. tobytearray (); objectinputstream OIS = new objectinputstream (bis); Return Ois. readobject ();} Public String getstring () {return string;} public void setstring (string) {This. string = string;} public serializableobject getobj () {return OBJ;} public void setobj (serializableobject OBJ) {This. OBJ = OBJ ;}} class serializableobject implements serializable {Private Static final long serialversionuid = 1l ;}

To achieve deep replication, you need to read the binary input of the current object in the form of a stream, and then write the object corresponding to the binary data.

Due to the long length of the article, in order to make it easier for readers to read, I will include other introductions in another article (maybe I will divide them into two articles ), thank you for your comments and suggestions!

If you have any questions, contact egg.

Email: xtfggef@gmail.com Weibo:Http://weibo.com/xtfggef

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.