Overview of 23 design patterns and understandable examples

Source: Internet
Author: User
23 Design patterns (divided into three categories) because the content is from the Youdao cloud notes moved over, so the layout is a bit ugly, if there are deficiencies or errors also hope pointing.

Note that some design patterns (code) "Forms" are identical or similar, but "semantics" are quite different. Personally, the design pattern advocates a coding idea, not a specification.

Why you should use design mode. For code reuse, increase maintainability
Six principles of design pattern

1, opening and closing principle (Open close principle)

The opening and closing principle means: open to expansion, close to modification. When the program needs to expand, can not modify the original code, to achieve a hot-swappable effect. In short, this is to make the program more scalable and easy to maintain and upgrade. To achieve this, we need to use interfaces and abstract classes, which we'll refer to later in the specific design.

2, the Richter substitution principle (Liskov substitution principle)

The principle of the Richter substitution is one of the basic principles of object-oriented design. The Richter substitution principle says that where any base class can appear, subclasses must be present. LSP is the cornerstone of inheritance reuse, and only if the derived class can replace the base class, and the functionality of the Software Unit is not affected, the base class can be truly reused, and derived classes can add new behavior based on the base class. The principle of the Richter substitution is a supplement to the principle of closing off. The key step of realizing the opening and closing principle is abstraction, and the inheritance relation of the base class and subclass is the concrete realization of abstraction, so the principle of the Richter substitution is the specification of the concrete steps to realize abstraction.

3. The principle of reliance reversal (dependence inversion principle)

This principle is the basis of the open and closed principle, specific content: for the interface programming, rely on the abstract and not rely 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. It also has another meaning: reduce the coupling between classes. This shows that, in fact, design pattern is from large software architecture, easy to upgrade and maintenance of software design ideas, it emphasizes reducing dependence, reduce coupling.

5, Dimitri Law, also known as the least known principle (Demeter principle)

The least known principle is that an entity should interact with other entities as little as possible, making the system functional modules relatively independent.

6. Synthetic reuse principle (composite reuse principle)

The composite reuse principle refers to the use of compositing/aggregation as much as possible, rather than using inheritance.

Create pattern (total five kinds)

Factory method Pattern: Defines an interface for creating objects, letting subclasses decide which factory class to instantiate, and the factory pattern delays the creation process to subclasses.
Personal Summary: Flexible production of multiple objects through object factory
public class Factory_method {public static void main (string[] args) {animalsfactory animalsfactory = NE
        W animalsfactory ();
        Create a Cat object from the factory Animals cat = Animalsfactory.getanimals ("cat");
        Create a dog object through the factory Animals dog = Animalsfactory.getanimals ("dog");  Cat.name ();
    Dog.name ();
 
}} interface Animals {//animal void name ();}
    Class Cat implements animals{//cat @Override public void name () {System.out.println (' This is a cat '); 
    } class Dog implements animals{//dog @Override public void name () {System.out.println (' This is a Dog '); } class Animalsfactory {//animal factory public Animals getanimals (String name) {if (Name.equalsignorecase ("Cat
        ") Return to New Cat ();
        else if (Name.equalsignorecase ("Dog")) Return to New Dog ();
    else return null; }
}


Abstract Factory pattern: Provides an interface to create a series of related or interdependent objects without specifying their specific classes.
Personal Summary: Factory mode >> a factory, a variety of objects; abstract Factory pattern >> an abstract factory, a variety of factories, each factory can produce many kinds of objects
public class Abstract_factory {//Factory Builder: Production of specific factory public static abstractfactory GetFactory (String factoryname) {
        if (Factoryname.equalsignorecase ("Animals")) return to New Animalsfactory ();
        else if (Factoryname.equalsignorecase ("others")) return to New Othersfactory ();
    else return null; public static void Main (string[] args) {//Production animal factory abstractfactory animalsfactory = GetFactory ("Animal
        S ");
        Create a Cat object through the animal factory Animals cat = Animalsfactory.getanimals ("cat");
    Cat.name ();
 
}} interface Animals {//animal void name ();}
    Class Cat implements animals{//cat @Override public void name () {System.out.println (' This is a cat '); } class Animalsfactory extends abstractfactory{//animal Factory public Animals getanimals (String name) {if (name.equ
        Alsignorecase ("Cat") return to New Cat ();
    else return null; } @Override Public OBject GetObject () {return null;
    } class Othersfactory extends abstractfactory{//other factory public Object GetObject () {return null;
    @Override public Animals getanimals (String name) {return null;
    The abstract class Abstractfactory {//Abstraction factory abstract public Animals getanimals (String name);
Abstract public Object getObject (); }


Singleton mode: guarantees that a class has only one instance and provides a global access point to access it.
Personal Summary: Create a single object within the class, by setting the constructor permissions, so that the class can not create objects outside
public class Singleton {public
     
    static void Main (string[] agrs) {The earth earth
        = Earth.getearth ();
        System.out.println (Earth.getage ());
    }
 
There are a number of ways to create a single instance object, the following is a more commonly used method, and the appropriate way to select it.
class Earth {  //Allow only one object to be created
    //Create a unique object
    private static earth earth = New Earth ();
    The constructor access must be private
    private Earth () {}
    ///Get Unique object public
    static Getearth () {return earth
        ;
    }
    private int age = 1000;
    public int getage () {return age
        ;
    }
}


Builder pattern: Separates a complex build from its presentation, allowing the same build process to create different representations.
Personal Summary: A number of basic components will not change, through builder, combination, building complex objects, to achieve separation
public class Builderdemo {public static void main (string[] args) {Pricebuilder Pricebuilder = new Pricebui
        Lder ();
        System.out.println ("Car1 and Car2:" +pricebuilder.car1andcar2 ());
    System.out.println ("Car1 and Bus:" +pricebuilder.car1andbus ());
    }//Basic components interface Car {}//Basic component 1 class CAR1 implements car{int price = 20;}//Basic component 2 class CAR2 implements car{
int price = 90;
        ///Basic Component 3 class Bus {int price =/} class Pricebuilder {//CAR1 and CAR2 total prices public int car1andcar2 () {
        int priceOfCar1 = new Car1 (). Price;
        int priceOfCar2 = new Car2 (). Price;
    return priceofcar1+priceofcar2;
        The total price of//CAR1 and bus is public int car1andbus () {int priceOfCar1 = new Car1 ().
        int priceofbus = new Bus (), price;
    return priceofcar1+priceofbus; }
}


Prototype pattern: Specifies the type of object to create with a prototype instance, and creates a new object by copying the prototypes.
Personal Summary: Copy the object and return it to the caller, the object needs to inherit cloneable and rewrite the Clone () method
public class Prototype implements cloneable{
 
    private String message = "Hello";
     
    Public Object Clone () throws clonenotsupportedexception{
        Prototype proto = (Prototype) super.clone ();
        Operation Clone Object
        proto.message = "world!";
        return proto; 
    }
     
    public static void Main (string[] args) throws clonenotsupportedexception {
        Prototype p = (Prototype) new Prototype (). Clone ();
        Manipulating the cloned object
        System.out.println (p.message);
    }

Structure mode (total seven kinds)

Adapter Mode: Converts the interface of a class into another interface that the customer expects. Adapter mode makes it possible for those classes that cannot work together because of incompatible interfaces.
Personal Summary: Bridging the functionality of two incompatible, independent interfaces enables them to work together. The adapter acts as a mediator.
public class Adapter {public
 
    static void Main (string[] args) {
        //compatible with advanced features common player player player
        = new player (); C5/>player.play ();
    }
Ordinary player
interface MediaPlayer {public
    void play ();
}
Advanced Player
Interface Advancemediaplayer {public
    void PlayVideo ();
}
//

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.