Overview of Java's 23 design patterns and the principles of 6 design patterns

Source: Internet
Author: User

23 Types of Java design pattern analysis

I. Overview 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.

Specific as follows:

Among the created types are:

Singleton, Singleton mode: guarantees that a class has only one instance and provides a global access to it

Point

Abstract Factory, Abstraction Factory: Provides an interface to create a series of related or interdependent objects,

You do not need to specify their specific classes.

Factory method, Factory methods: Define an interface for creating objects, let subclasses decide which class to instantiate, and Factory method to defer instantiation of a class to subclasses.

Builder, Build mode: Separates the construction of a complex object from his presentation, allowing the same build process to create different representations.

V. Prototype, prototype mode: Specifies the kind of object created with the prototype instance, and creates a new object by copying the prototypes.

Behavioral types are:

Vi. Iterator, Iterator mode: Provides a way to sequentially access individual elements of an aggregated object without exposing the object's internal representation.

VII. Observer, Observer pattern: Defines a one-to-many dependency between objects, and when an object's state changes, all objects that depend on it are notified of Automatic Updates.

Template method: Define the skeleton of an algorithm in an operation, and defer some steps into the subclass, Templatemethod so that subclasses can redefine the algorithm to some specific steps without changing the structure of an algorithm.

commands, Command mode: Encapsulates a request as an object, allowing you to parameterize the customer with different requests, queue requests and log requests, and support revocable operations.

State mode: Allows an object to change his behavior when its internal state changes. The object seems to have changed his class.

XI. strategy, Strategy mode: Define a series of algorithms, encapsulate them one by one, and allow them to replace each other, this mode allows the algorithm to be independent of the customers who use them.

12, China of Responsibility, responsibility chain mode: Enables multiple objects to have the opportunity to process the request, thus avoiding the coupling between the requested communicated and the receiver

13, Mediator, Mediator mode: Encapsulates the object interaction of some columns with a mediation object.

14. Visitor, Visitor mode: represents an operation that acts on elements of an object structure, allowing you to define new actions that act on this element without changing the individual element classes.

XV, interpreter, interpreter mode: Given a language, define a representation of his grammar, and define a

An interpreter that uses this representation to interpret sentences in a language.

16. Memento, Memo mode: captures the internal state of an object without destroying the object, and saves the state outside the object.

Structural types are:

17, Composite, combination mode: The object is combined into a tree structure to represent a partial overall relationship, and Composite makes the user consistent with the use of individual objects and composite objects.

18, facade, appearance mode: To provide a consistent interface for a set of interfaces in the subsystem, Fa?ade provides a high-level interface, which makes the subsystem easier to use.

19, Proxy, Agent mode: Provide a proxy for other objects to control access to this object

20, Adapter, adapter mode: To convert a class of interfaces into another interface that the customer wants, the Adapter mode makes it possible for those classes to work together because the interface is incompatible and cannot work together.

21, Decrator, Decoration mode: Dynamically add some additional responsibilities to an object, the Decorator mode is more flexible than generating subclasses in terms of the added functionality.

22. Bridge mode: Separates the abstract part from its realization, so that they can change independently.

23, Flyweight, enjoy meta mode

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

The six principles of design pattern

General principle: 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, not to modify the original code, but to extend 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 such an effect, we need to use interfaces and abstract classes, and so on, which we will mention in the specific design later on.

1. Single Duty principle

Do not have more than one cause of class changes, that is, each class should implement a single responsibility, if not, the class should be split.

2, the Richter replacement principle (Liskov Substitution Principle)

The principle of the substitution of the Richter scale (Liskov Substitution Principle LSP) is the basic principle of object-oriented design. The Richter substitution principle says that

Where any base class can appear, subclasses-can be seen. 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. A Frombaidu

Encyclopedia

In the history substitution principle, subclasses do not override and overload the methods of the parent class as much as possible. Because the parent class represents a well-defined structure, the sub-class should not arbitrarily destroy it by interacting with the outside world through this canonical interface.

3. Dependence reversal principle (dependence inversion Principle)

This is the basis of the open and close principle, the specific content: interface-oriented programming, dependent on the abstract and not dependent on the specific. When writing code, a specific class is used, not interacting with a specific class, but interacting with the upper interface of a specific class.

4. Interface Isolation principle (Interface segregation Principle)

This principle means that there is no way for subclasses to be implemented in each interface, and if not, the interface should be split. Make

Using multiple isolated interfaces is better than using a single interface (multiple interface methods to assemble one interface).

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

It means that a class knows as little as possible about the classes it relies on. This means that no matter how complex a dependent class is, the logic should be encapsulated inside the method and provided externally through the public method. This way, the class can be minimized when the dependent class changes.

The least known principle is another way of saying it: communicate only with direct friends. As long as there is a coupling relationship between classes, it is called a friend relationship. Coupling

are divided into dependencies, associations, aggregations, combinations, and so on. We call the class that appears as a member variable, method parameter, method return value as a direct friend. Local variables, temporary variables are not direct friends. We ask unfamiliar classes not to appear as local variables in the class.

6. Synthetic multiplexing principles (Composite reuse Principle)

The principle is to try to use the composition/aggregation approach first, rather than using inheritance.

Iii. Java 23 Design pattern A, creation 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.

First of all, the simple factory model does not belong to the 23 model involved, simple factory one-like: ordinary simple factory, multi-method simple factory, static method simple factory.

0. Simple Factory mode

The Simple Factory mode mode is divided into three types: 01, Normal

is to create a factory class that creates instances of classes that implement the same interface. First look at the diagram:

For example: (Let's give one by one examples of sending emails and text messages) first, create a common interface for both:

Public interface Sender {public    void Send ();}

Second, create the implementation class:

public class MailSender implements Sender {    @Override public    void Send () {    System.out.println Mailsender! ");}    } public class Smssender implements Sender {    @Override public    void Send () {    System.out.println ("This is SMS Sen Der! ");}    }

Finally, build the factory 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. println ("Please enter the correct type!"). ");         return null;)    }}

Let's test it out:

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!

02. Multiple Methods

is an improvement to the common factory method pattern, in the normal factory method pattern, if the passed string is faulted, the object cannot be created correctly, and multiple factory method patterns provide multiple factory methods to create the objects individually. Diagram:

Make the above code changes, change the next Sendfactory class on the line, as follows:

public class Sendfactory {public    Sender Producemail () {        return new MailSender ();       }            Public Sender producesms () {        return new Smssender ();}    }

The test classes are 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!

Related articles:

Java Design Patterns-six principles of design patterns

24 Design Patterns and 7 principles in Java

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.