Design mode (Patterns)

Source: Internet
Author: User

Design mode (Patterns)

--the basis of reusable object-oriented software

Design patterns are a set of reusable, most known, categorized purposes, code design experience Summary. Design patterns are used in order to reuse code, make code easier for others to understand, and ensure code reliability. There is no doubt that design patterns in others in the system are multi-win, design patterns so that code is truly engineering, design patterns are the cornerstone of software engineering, like a block of bricks and tiles in the building. The rational use of design patterns in the project can solve many problems perfectly, each of which has corresponding principles in the present, each of which describes a recurring problem around us, and the core solution of the problem, which is why it can be widely used. This chapter is the beauty of Java [from rookie to master evolution] series of design patterns, we will be a combination of theory and practice in this chapter of the study, hope that the vast number of process enthusiasts, learn the design model, do a good software engineer!

Enterprise-level project combat (with source) address :

23 Modes Java implementation of the source codeHttp:// %b6

I. Classification of design Patterns

In general, design patterns fall into three broad categories:

Create five types of models: Factory method mode, abstract Factory mode, singleton mode, builder mode, prototype mode.

Structure mode, a total of seven kinds: Adapter mode, adorner mode, proxy mode, appearance mode, bridging mode, combined mode, enjoy the meta-mode.

There are 11 types of behavioral Patterns: Strategy mode, template method mode, observer mode, iteration sub-mode, responsibility chain mode, Command mode, Memo mode, state mode, visitor mode, mediator mode, interpreter mode.

In fact, there are two types: concurrency mode and thread pool mode. Use a picture to describe it as a whole:

First, the six principles of design pattern

1. Opening and closing principle (Open Close Principle)

The open and closed principle is to say to the expansion opening, to modify the closure . When the program needs to expand, can not modify the original code, to achieve a hot plug effect. So a nutshell is: In order to make the program good extensibility, easy to maintain and upgrade. To achieve this, we need to use interfaces and abstract classes, which we will refer to later in the specific design.

2. The principle of substitution on the Richter scale (Liskov Substitution Principle)

One of the fundamental principles of object-oriented design of the Richter substitution principle (Liskov Substitution Principle LSP). The Richter substitution principle says that where any base class can appear, subclasses must be able to appear. LSP is the cornerstone of inheritance reuse, only if the derived class can replace the base class, the function of the Software unit is not affected, the base class can be really reused, and the derived class can also add new behavior on the basis of the base class. The principle of substitution on the Richter scale is a supplement to the principle of "open-closed". The key step in implementing the "open-close" principle is abstraction. The inheritance of the base class and subclass is the concrete implementation of abstraction, so the principle of the substitution of the Richter scale is the specification of the concrete steps to realize the abstraction. --from Baidu Encyclopedia

3. Dependence reversal principle (dependence inversion Principle)

This is the basis of the open and close principle, the specific content: TRUE interface programming, relying on abstraction and not dependent on the specific.

4. Interface Isolation principle (Interface segregation Principle)

This principle means that using multiple isolated interfaces is better than using a single interface. or a reduction of the coupling between the class meaning, from here we see, in fact, the design pattern is a software design ideas, from the large software architecture, in order to upgrade and maintenance convenience. So there are multiple occurrences: reducing dependency and reducing coupling.

5, Dimitri Law (least known principle) (Demeter Principle)

Why is it called the least known principle, that is to say: an entity should be as small as possible interaction with other entities, so that the system function module is relatively independent.

6. Synthetic multiplexing principles (Composite reuse Principle)

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

Third, Java 23 design mode

Starting from this piece, we introduce in detail the concepts of 23 design Patterns in Java, application scenarios and other situations, and combine their characteristics and design patterns to analyze the principles.

1. Factory method Mode (Factory methods)

The factory method pattern is divided into three types:

11, the Common factory model , is to establish a factory class, the implementation of the same interface for some classes to create instances. First look at the diagram:

Singleton mode (Singleton)

A singleton object (Singleton) is a common design pattern. In Java applications, singleton objects guarantee that only one instance of the object exists in a JVM. There are several benefits to this model:

1, some classes are created more frequently, for some large objects, this is a lot of overhead.

2, eliminate the new operator, reduce the use of system memory frequency, reduce the GC pressure.

3, some classes such as the exchange's core trading engine, control the trading process, if the class can create multiple words, the system is completely chaotic. (for example, an army has multiple commanders at the same time command, it will certainly mess), so only using a singleton mode can ensure that the core trading server independently control the entire process.

First, let's write a simple singleton class:

[Java]View Plaincopy
  1. public class Singleton {
  2. /* Holds private static instances, prevents references, and assigns null here to enable lazy loading */
  3. private static Singleton instance = NULL;
  4. /* Private construction method to prevent instantiation of */
  5. Private Singleton () {
  6. }
  7. /* Static Engineering method, create instance */
  8. public static Singleton getinstance () {
  9. if (instance = = null) {
  10. Instance = new Singleton ();
  11. }
  12. return instance;
  13. }
  14. /* If the object is used for serialization, you can ensure that the object remains consistent before and after serialization.
  15. Public Object Readresolve () {
  16. return instance;
  17. }
  18. }

This class can meet the basic requirements, but, like this no thread-safe class, if we put it into multi-threaded environment, there will be problems, how to solve? We will first think of the GetInstance method plus the Synchronized keyword, as follows:

[Java]View Plaincopy
    1. public static synchronized Singleton getinstance () {
    2. if (instance = = null) {
    3. Instance = new Singleton ();
    4. }
    5. return instance;
    6. }

However, the Synchronized keyword lock is the object, such usage, will be degraded in performance, because each call to getinstance (), the object must be locked, in fact, only when the first time the object is created to lock, and then do not need, so, This place needs to be improved. Let's change to the following:

[Java]View Plaincopy
    1. public static Singleton getinstance () { 
    2.         if ( instance = = null) { 
    3.             synchronized ( Instance) { 
    4.                  if (instance = = null) { 
    5.                      instance = new Singleton ();  
    6.                 } 
    7.             } 
    8.        }  
    9.         return instance; 
    10.    }  

Seems to solve the problem mentioned earlier, the Synchronized keyword is added to the internal, that is, when the call is not required to lock, only when the instance is null, and create the object only need to lock, performance has a certain elevation. However, there may be problems with this, see the following: creating objects and assigning operations in Java directives is done separately, that is, instance = new Singleton (); The statement is executed in two steps. However, the JVM does not guarantee the sequencing of the two operations, which means that it is possible for the JVM to allocate space for the new singleton instance and then assign the value directly to the instance member before initializing the singleton instance. This can be a mistake, we take a, b two threads as an example:

A>a, B Threads Enter the first if judgment at the same time

B>a first enters the synchronized block, because instance is null, so it executes instance = new Singleton ();

C> because of the optimization mechanism inside the JVM, the JVM first draws some blank memory allocated to the singleton instance and assigns it to the instance member (note that the JVM does not start initializing the instance at this time), and a leaves the synchronized block.

D>b enters the synchronized block because instance is not NULL at this time, so it immediately leaves the synchronized block and returns the result to the program that called the method.

E> this time the B thread intends to use the singleton instance, but finds that it was not initialized, and the error occurred.

So the program is still possible error, in fact, the program is very complex in the process of operation, from this point we can see, especially in the writing multi-threaded environment of the program is more difficult, challenging. We have further optimized the program:

[Java]View Plaincopy
    1. private Static Class singletonfactory{
    2. private static Singleton instance = new Singleton ();
    3. }
    4. public static Singleton getinstance () {
    5. return singletonfactory.instance;
    6. }

The reality is that the singleton pattern uses an internal class to maintain the implementation of the Singleton, and the mechanism inside the JVM guarantees that when a class is loaded, the loading process of the class is thread-mutually exclusive. So when we first call getinstance, the JVM can help us ensure that instance is created only once and that the memory assigned to instance is initialized so we don't have to worry about the problem. At the same time, the method only uses the mutex mechanism when the first call is made, which solves the low performance problem. This allows us to briefly summarize a perfect singleton pattern:

[Java]View Plaincopy
  1. public class Singleton {
  2. /* Private construction method to prevent instantiation of */
  3. Private Singleton () {
  4. }
  5. /* Use an inner class here to maintain the singleton */
  6. private Static Class Singletonfactory {
  7. private static Singleton instance = new Singleton ();
  8. }
  9. /* Get instance */
  10. public static Singleton getinstance () {
  11. return singletonfactory.instance;
  12. }
  13. /* If the object is used for serialization, you can ensure that the object remains consistent before and after serialization.
  14. Public Object Readresolve () {
  15. return getinstance ();
  16. }
  17. }

In fact, it is perfect, not necessarily, if an exception is thrown in the constructor, the instance will never be created and will be faulted. So, the very perfect thing is not, we can only according to the actual situation, choose the most suitable for their own application of the implementation of the scenario. Others do this: because we only need to synchronize when creating the class, it is also possible to create the Synchronized keyword separately, as long as the creation and getinstance () are created separately:

[Java]View Plaincopy
  1. public class Singletontest {
  2. private static Singletontest instance = NULL;
  3. Private Singletontest () {
  4. }
  5. private static synchronized void Syncinit () {
  6. if (instance = = null) {
  7. Instance = new Singletontest ();
  8. }
  9. }
  10. public static Singletontest getinstance () {
  11. if (instance = = null) {
  12. Syncinit ();
  13. }
  14. return instance;
  15. }
  16. }

With performance in mind, the entire program only needs to create one instance at a time, so performance has no effect.

Supplement: Use Shadow instance to synchronize updates for properties of Singleton objects

[Java]View Plaincopy
  1. public class Singletontest {
  2. private static Singletontest instance = NULL;
  3. Private Vector properties = null;
  4. Public Vector getProperties () {
  5. return properties;
  6. }
  7. Private Singletontest () {
  8. }
  9. private static synchronized void Syncinit () {
  10. if (instance = = null) {
  11. Instance = new Singletontest ();
  12. }
  13. }
  14. public static Singletontest getinstance () {
  15. if (instance = = null) {
  16. Syncinit ();
  17. }
  18. return instance;
  19. }
  20. public void Updateproperties () {
  21. Singletontest shadow = new Singletontest ();
  22. Properties = Shadow.getproperties ();
  23. }
  24. }

Learning through a singleton pattern tells us:

1, the single-case model is simple to understand, but the specific implementation is still a certain degree of difficulty.

2, synchronized keyword lock is the object, in use, it must be used in the appropriate place (note the need to use the lock object and process, may not be the whole object and the whole process need to lock).

Here, the singleton mode has been basically finished, at the end, I suddenly think of another problem, is the use of static methods of the class, to achieve the effect of a single-case model, is also feasible, here are the differences?

First, a static class cannot implement an interface. (It's possible from a class point of view, but that destroys the static.) Because static modifiers are not allowed in the interface, they are non-static even if implemented

Second, a singleton can be delayed initialized, and static classes are typically initialized in the first load. Delay loading is because some classes are large, so lazy loading can help improve performance.

Again, a singleton class can be inherited, and his method can be overwritten. However, static class internal methods are static and cannot be overwritten.

Finally, the Singleton class is more flexible, after all, from the implementation is just a common Java class, as long as the basic needs of the singleton, you can do in the arbitrary implementation of some other functions, but static class does not. From the above summary, the basic can see the difference between the two, but, on the other hand, we finally realized that the singleton pattern, the interior is a static class to achieve, so, the two have a great correlation, but we consider the level of the problem is different. The combination of two ideas to create a perfect solution, just like HashMap using array + linked list to achieve the same, in fact, many things in life are so, alone with different methods to deal with problems, there are always advantages and disadvantages, the most perfect way is to combine the advantages of each method, to best solve the problem!

Design Patterns in Java

1, Factory mode: Customer class and factory class separate. Consumers need a product at any time, just request it from the factory. Consumers can accept new products without modification. The disadvantage is that when the product is modified, the factory class should also make corresponding changes. such as: How to create and how to provide to the client.

2, Construction mode: The internal appearance of the product and the production process of the product is separated, so that a construction process to produce a different internal representation of the product object. The construction mode allows the internal representation of the product to change independently, and the customer does not need to know the details of the product internals. The construction model can enforce a step-by-stage construction process.
3, factory method mode: The Core factory class is no longer responsible for the creation of all products, but the specific creation of the work to the sub-class to do, become an abstract factory role, only responsible for the specific factory class must be implemented interface, and do not touch which product class should be instantiated this detail.
4. Original model mode: By giving a prototype object to indicate the type of object to be created, and then creating more objects of the same type with the method of copying the prototype object. The original model mode allows the product class to be dynamically increased or decreased, and the product class does not need to have any predetermined hierarchy structure, and the original model pattern applies to any hierarchy structure. The disadvantage is that each class must be equipped with a clone method.
5. Singleton mode: A singleton mode ensures that a class has only one instance, and instantiates itself and provides this instance singleton pattern to the whole system. Singleton mode should only be used when there is a real "single instance" requirement.
6, adapter (transformer) mode: The interface of a class is transformed into another interface that the client expects, so that the two classes that are not able to work together because of the interface cause mismatch can work together. The adaptation class can return an appropriate instance to the client based on the parameters.
7, Bridge mode: The abstraction and implementation of decoupling, so that they can be independent changes, that is, the strong association between them into a weak association, that is, the abstraction and implementation of a software system between the use of combination/aggregation relationship rather than inheritance, so that the two can be independent changes.
8. Composition mode: The composition mode organizes the objects into the tree structure, which can be used to describe the relationship between the whole and the parts. A compositing pattern is a pattern that handles the tree structure of an object. The composition mode represents the relationship of the part and the whole with the tree structure. The compositing mode allows the client to treat a single constituent object in the same way as a composite object made up of them.
9, Decorative mode: Decorative mode to the client transparent way to extend the function of the object, is an alternative to the inheritance relationship, providing more flexibility than inheritance. Dynamically adds functionality to an object that can be undone on the fly. Adds a very large amount of functionality resulting from the combination of some basic functions.
10, the façade mode: external and a subsystem of communication must be through a unified façade object. Façade mode provides a high-level interface that makes subsystems easier to use. Each subsystem has only one façade class, and this façade class has only one instance, meaning it is a singleton pattern. But the entire system can have multiple façade classes.
11. Enjoy meta Mode: Flyweight is the most lightweight of the boxing game. The enjoy meta-mode efficiently supports a large number of fine-grained objects in a shared manner. The key to sharing the shared meta-mode is to differentiate between intrinsic state and external state. The intrinsic state is stored inside the element, and does not vary with the environment. The state of the outer Yun is changed with the change of the environment. The outer state can not affect the intrinsic state, they are independent of each other. Separates the states that can be shared and the states that cannot be shared from the regular class, removing the state that cannot be shared from the class. Instead of creating the shared object directly, the client should use a factory object responsible for creating the object being shared. The enjoy meta-mode significantly reduces the number of objects in memory.
12, Proxy mode: Proxy mode provides a proxy object for an object, and the proxy object controls the reference to the source object. An agent is a person or an institution acting on behalf of another person or an institution. In some cases, the client does not want or cannot refer directly to an object, and the proxy object can act as an intermediary directly between the customer and the target object. The client cannot distinguish between a proxy subject object and a real subject object.   Proxy mode can not know the real proxy object, but only hold a proxy object interface, this time the proxy object can not create the proxy object, the proxy object must have the other role of the system to create and pass in. 13, the responsibility chain mode: In the chain of responsibility model, many objects by each object to its next-generation reference and to form a chain. The request is passed on this chain until an object on the chain decides to process the request. The customer does not know which object on the chain is ultimately processing the request, and the system can dynamically reorganize the chain and assign responsibility without affecting the client. The processor has two choices: take responsibility or push the responsibility to the other person. A request can eventually not be accepted by any receive-side object.
14. Command mode: The command mode encapsulates a request or operation into an object. The command mode divides the responsibility for issuing the command and the responsibility for executing the command, delegating it to different objects. The command pattern allows the requesting party to be independent of the sending party, so that the requesting party does not have to know the interface of the party receiving the request, not to know how the request was received, and whether the operation was executed, when it was executed, and how it was executed. The system supports undo of the command.
15, Interpreter mode: Given a language, the interpreter pattern can define a representation of its grammar and provide an interpreter at the same time. The client can use this interpreter to interpret the sentences in the language. The interpreter pattern describes how to interpret these statements using a pattern design after having a simple grammar. The language mentioned in the interpreter pattern refers to any combination that any interpreter object can interpret. In the interpreter pattern, you need to define a hierarchy of command classes that represent grammars, which is a series of composition rules. Each command object has an explanatory method that represents the interpretation of the Command object. Any permutation combination of objects in the hierarchy of command objects is a language.
16. Iterative sub-pattern: Iterative sub-patterns can sequentially access an element in a cluster without exposing the aggregated interior representation. Aggregates are collectively called aggregates, and clustered objects are container objects that can contain a set of objects. The iterative sub-pattern encapsulates the iterative logic into a separate sub-object, which is separated from the aggregation itself. Iterative sub-patterns simplify the aggregation of the interface. Each clustered object can have one or more iteration sub-objects, and the iteration state of each iteration can be independent of each other. Iterative algorithms can be independent of aggregate role changes.
17. Mediator Mode: The Mediator pattern wraps a series of objects interacting in a way that makes these objects unnecessary to each other. So that they can be loosely coupled. When the role of some objects changes, it does not immediately affect the effect of other objects. Ensure that these effects can change independently of each other. The mediator model converts many-to-many interactions into one-to-many interactions. The Mediator pattern abstracts the behavior and collaboration of objects, and separates them from the interactions of other objects on small-scale behaviors.
18. Memo Mode: A Memo object is an object used to store a snapshot of the internal state of another object. The purpose of the memo mode is to capture the state of an object without destroying the package, and to externally and store it so that it can be restored to the stored state at the appropriate time in the future.
19. Observer mode: The Observer pattern defines a multiple-team dependency, allowing multiple observer objects to listen to a Subject object at the same time. When the subject object changes in state, all observer objects are notified so that they can automatically update themselves.
20. State mode: state mode allows an object to change behavior when its internal state changes. This object looks like it has changed its class. State mode wraps the behavior of the object being studied in a different state object, and each state object belongs to a subclass of an abstract state class. The intent of the state pattern is to change the behavior of an object as it changes its internal state. State mode requires the creation of a subclass of a State class for each of the possible states of a system. When the state of the system changes, the system changes the selected subclass.
21, Policy mode: The policy mode for a set of algorithms, each algorithm is encapsulated in a separate class with a common interface, so that they can be replaced with each other. The policy pattern allows the algorithm to change without affecting the client. The strategy model separates behavior from the environment. The Environment class is responsible for maintaining and querying behavior classes, and various algorithms are available in specific policy classes. Because the algorithm and the environment independent, the algorithm increases or decreases, the modification will not affect the environment and the client.
22. Template method Pattern: Template method mode prepares an abstract class, implements some of the logic in the form of concrete methods and concrete constructors, and then declares some abstract methods to force subclasses to implement the remaining logic. Different subclasses can implement these abstract methods in different ways, thus having different implementations of the remaining logic. First, a top-level logical framework is developed, and the details of the logic are left to the specific subclasses to implement.
23. Visitor Mode: The purpose of the visitor pattern is to encapsulate some operations that are applied to a data structure element. Once these operations need to be modified, the data structure that accepts the operation can remain unchanged. The visitor pattern is suitable for systems with relatively indeterminate data structures, which frees up the coupling between the structure and the operation of the structure so that the set of operations can evolve relatively freely. The visitor pattern makes it easy to add new operations, which is to add a new visitor class. The visitor pattern concentrates the behavior on a visitor object, rather than spreading it across a node class. When you use the visitor pattern, you put as much of the object-browsing logic in the visitor class as possible, rather than in its subclasses. The visitor pattern can access member classes belonging to different hierarchical structures across hierarchical structures of several classes.

Design mode (Patterns)

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: 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.