Common design patterns summarized :( a) create a schema

Create a schema

Create schema instantiation process of the abstract class, with the object can be created using the object separation process.

Simple factory pattern (Simple Factory Pattern)

Aliases

  • Static factory method (Static Factory Method) mode

Mode motivation

Consider a simple software application scenario, a software system may provide the appearance of a plurality of different buttons (e.g., radio button, a rectangle button, diamond button, etc.), these buttons are derived from the same base class, the base class but differ in succession subclass modify some of the properties so that they can present a different look, if we want to use these buttons, the button does not need to know the names of these specific classes, only need to know the parameters indicate a button class, and provides a call convenient method, the parameters passed to the method to return a corresponding button object, this time, you can use a simple factory pattern.

Schema Definition

Examples of different classes can be returned in accordance with different parameters. Simple factory pattern to define a special class to other classes responsible for creating an instance, the instance is created normally have a common parent class.
The point is simple factory pattern: when what you need, just need to pass the right parameters, you can get the object you need, without having to know the details of its creation.

Mode structure

  • Factory: Factory roles
    factories role is responsible for implementing internal logic all create instances

  • Product: Product roles abstract
    abstract Product role is the parent of all objects created, responsible for describing the public interface common to all instances

  • ConcreteProduct: role of specific products
    specific role is to create a product target, all objects created are serving as an example of a specific class of this role.

Mode Application

JDK class library widely used simple factory mode, the java.text.DateFormat class tool, which is used to format a local date or time.

public final static DateFormat getDateInstance();
public final static DateFormat getDateInstance(int style);
public final static DateFormat getDateInstance(int style,Locale
locale);

Java encryption technology
to obtain key generator different encryption algorithms:

KeyGenerator keyGen=KeyGenerator.getInstance("DESede");

Create a password control:

Cipher cp=Cipher.getInstance("DESede");

advantage

  • Factory class contains the necessary logic judgment, can decide which instance of a product class is created at what time the client may be exempted from the responsibility to create product objects directly, but only "consumer" product; a simple factory pattern achieved through the practice of responsibility the division, which provides specialized factory class for creating objects.
  • Clients do not need to know the class name specific product category created only need to know the specific product class corresponding parameters can be, for some complex class name, a simple factory pattern can reduce the amount of user memory.
  • By introducing the configuration file, you can change and add new specific product category without modifying any client-side code and improve the flexibility of the system to some extent.

Shortcoming

  • Since the factory class centralizes all product creation logic, once it does not work, the entire system must be affected.
  • Using a simple model will increase the number of factory classes in the system, increases the complexity and the difficulty of understanding the system in a certain program.
  • System expansion difficult, once the new product will have to add logic to modify the plant, when there are many types of products, may cause the plant logic is too complicated, is not conducive to the expansion and maintenance of the system.
  • Simple factory pattern due to the use of static factory method, resulting in the role of the factory can not form a hierarchy based on inheritance.

Factory method model (Factory Method Pattern)

Aliases

  • Factory Pattern
  • Virtual constructor (Virtual Constructor) mode
  • Polymorphic plant (Polymorphic Factory) mode

Mode motivation

No longer designed to unify a button factory class is responsible for creating all the products, but rather the creation of a specific button to specialized subclasses to the factory completed, we first define an abstract factory class button, and then define concrete factory class generating a radio button, a rectangle button, button or the like diamond, they implement the abstract methods defined in the button class factory. This abstract result that such a structure can introduce new products without modifying the concrete factory class, if the new button type appears, only need to create a concrete factory class for this new type of button you can get examples of the new button, a feature that will undoubtedly make the factory method pattern has advantages beyond simple factory pattern, more in line with "the principle of opening and closing."

Schema Definition

In the factory method mode, the factory parent class is responsible for defining create products object's public interface, the factory subclass is responsible for generating a particular target products, the aim is to instantiate operation of the product class delay to the plant subclass completed, i.e., by determining whether the factory subclass which a specific product class to instantiate.

Mode structure

  • Product: abstract product
  • ConcreteProduct: Specific products
  • Factory: Abstract Factory
  • ConcreteFactory: Concrete Factory

Mode Application

The JDBC factory method:

Connection conn=DriverManager.getConnection("jdbc:microsoft:sqlserver://loc
alhost:1433; DatabaseName=DB;user=sa;password=");
Statement statement=conn.createStatement();
ResultSet rs=statement.executeQuery("select * from UserInfo");

advantage

  • In the factory method pattern, factory method to create products needed by customers, but also to customers which hides the specific product class will be instantiated this detail, users only need to worry about the plant required for the corresponding product without concern created details, or even know the name of the class specific product category.
  • Polymorphism plant design is based on the role and character of the product is the key factory method pattern. It enables the plant can autonomously determine what product object is created, and how to create the details of the object is completely encapsulated in the concrete factory. The reason why the method of the factory mode is also called polymorphic factory mode, because all of the specific factory classes with the same abstract parent class.
  • When adding new products in the system, no need to modify the interface abstraction abstract factory and product offers without having to modify the client, there is no need to modify other concrete plants and concrete products, and just add a specific plant and specific products on it. Thus, scalability of the system will become very good, full compliance with "the principle of opening and closing."

Shortcoming

  • When adding a new product, you need to write a new class of specific products, but also to provide the corresponding concrete factory class, the number of pairs of the class system increases, the complexity of the system to some extent, there is more the class needs to be compiled and run, will bring some additional overhead system.
  • Taking into account the scalability of the system, requires the introduction of abstraction layer, are defined in the abstraction layer using the client code, the system increases the abstraction and the difficulty of understanding, and may need to use the DOM, reflection ART When implemented, increase the difficulty of implementing the system.

Abstract Factory (Abstract Factory)

Mode motivation

Sometimes we need a facility can provide multiple product object, rather than a single product target.

Schema Definition

Create a series of related or dependent objects interface, without specifying their concrete classes. Abstract Factory pattern, also known as Kit, belonging schema object creation.

Mode structure

  • AbstractFactory: Abstract Factory
  • ConcreteFactory: Concrete Factory
  • AbstractProduct: abstract product
  • Product: specific products

advantage

  • Abstract factory pattern isolated generate specific classes so customers do not need to know what is being created. Because of this isolation, replacement of a particular plant becomes relatively easy. All concrete plants have achieved those public interface defined in the abstract factory, so just change the specific instance of the factory, you can change the behavior of the entire software system to some extent. Further, the application may be implemented abstract factory design pattern object with high cohesion and low coupling, so abstract factory model has been widely used.
  • When a product family of multiple objects are designed to work together, it can ensure that clients always use only objects in the same product family. This need for some to determine its behavior according to the current environment of software systems, is a very practical design mode.
  • Adding new concrete factory and product family easily, without modifying the existing system, in line with "the principle of opening and closing."

Shortcoming

  • When you add a new product object, difficult to extend the abstract factory to produce new types of products, this is because the provision of all possible sets of products have been created in the abstract factory role, to support new types of products it means that interface be extended, which would involve modifications to the abstract factory role and all its subclasses will obviously bring greater inconvenience.
  • The principle of opening and closing of the tilt of the (increase in new factories and easy product family, adding new product hierarchy trouble).

Degradation of the factory pattern

When the abstract factory pattern in every concrete factory class creates only one product target, that is, there is only one product hierarchy, the abstract factory pattern degenerate into a factory method pattern;
when the factory method pattern abstract plant consolidations and plant-specific, providing a unified when the factory to create products object and create an object factory method is designed for static methods, the factory method pattern degenerate into a simple factory pattern.

Builders mode (Builder Pattern)

Mode motivation

Whether it is or in the software system, there are some complex object in the real world, they have a plurality of elements, such as cars, comprising a wheel, a steering wheel, a transmitter and other components. For most users, without knowing the details of these components are assembled, hardly a component used alone, but the use of a complete car, can be designed and described by its builder mode, the builder pattern and the assembling process can be separated, step by step, to create a complex object. Users only need to specify the type of complex objects the object can be obtained, without having to know the specific details of its internal structure.

In software development, there are also a large number of complex objects like cars, they have a series of member properties, attributes some of these members is a member of reference type objects. And in these complex objects, there may be some restrictions, such as certain attributes no value is complex objects can not be used as a complete product; before the assignment of some property must follow a certain order, a property has no value, other property and so may not be assigned.

Complex object is equivalent to a car to be built, and properties of the object corresponds to part of the car, the construction process is equivalent to the product of the process of combination of components. Since the process combination of components is very complicated, and therefore, the combination process of these components are often "externalized" to a called an object builder, the builder returned to the client is an already built complete product object is completed, and the user does not need concern the object contains properties and their assembly methods, this is the mode of motivation builder mode.

Schema Definition

It represents the construct and its separation of a complex object, such that the same build process can create different representations.

The builder pattern is a step by step to create a complex object, which allows the user can build them only by specifying the type and content of complex objects, users do not need to know the specific details of the interior of the building. The builder pattern belong to the type of object creation mode. Depending on the translation of Chinese, but also can be called the builder pattern generator mode .

Mode structure

  • Builder: abstract Builder
  • ConcreteBuilder: Specific builder
  • Director: commander
  • Product: Product roles

Abstract builder class defines a method of creating the product and return method;

Structure builder mode also introduces a commander like Director, the role of this class are mainly two: on the one hand it isolates the customer and the production process; on the other hand it is responsible for controlling the generation process of the product. Commander for abstract builder program, clients only need to know the specific type of builder, you can through the relevant class method commanders call the builder returns a complete product target

In the client code, without concern for product assembly process specific object, simply determine the specific type of builder can, builders constructed model will behave with the object of complex objects separated, so that the same construction process can create different performance.

Examples

KFC Package

The builder pattern may be used to describe how to create KFC package: Package is a complex object, which typically comprises staple part (such as hamburgers, chicken roll) and beverages (juice, cola, etc.), different packages have different composition section, and the attendant can KFC to customer demand, the assembly of these components step by step, a complete package structure, and returned to the customer.

advantage

  • In the builder mode, the client does not have to know the details of the internal composition of the product, the product itself and the process of creating the product decoupled so that the same creation process can create different product objects.
  • Each specific builders are relatively independent, regardless of other specific builder, so you can easily replace specific builder or add new concrete builder, users use different specific builder can get a different product objects.
  • You can more finely control the product creation process. The step of creating the complex decomposition products in different ways, so that the creation of clearer and more easy to use program to control the creation process.
  • Add a new concrete builder without modifying the original class library code to facilitate the expansion class commander for abstract builder class programming system, in line with "the principle of opening and closing."

Shortcoming

  • The builder pattern created products generally have more in common, which is part of similar, if the difference between a great product is not suitable to use the builder pattern, so its use is subject to certain restrictions.
  • If the internal changes in product complexity, may cause a lot of need to define concrete builder classes to implement this change, cause the system to become very large.

Mode Application

In many game software, including a sky map, ground, background part, including human characters, clothing, equipment and other components may be using the builder pattern design, create different types of maps with different specific builder or figures.

Singleton (Singleton Pattern)

Mode motivation

For some classes of systems, only one instance is important, for example, a system can contain multiple print job, but can only have a job are working; a system can be only one window manager or file system ; a system can have a timing device or ID (number) generator.

How to ensure that only one instance of a class, and this instance is easy to access it? Define a global variable can be sure that the object can be accessed at any time, but can not prevent us instantiate multiple objects.

A better solution is to let the only instance of the class itself responsible for saving it. This class can ensure that no other instance is created, and it can provide a method to access the instance. This is the motivation mode Singleton pattern.

Schema Definition

Singleton ensure only one instance of a particular class, and to instantiate the instance of the entire system and to provide this class is called singleton class that provides global access method.

Important single embodiment has three modes: First, only one instance of a class; second, it must create an instance of its own; it must provide their own three in this example the entire system. Singleton pattern is an object to create schema. Singleton and member list mode or single-mode state.

Mode structure

Pattern Analysis

Published 143 original articles · won praise 45 · views 70000 +

Guess you like

Origin blog.csdn.net/z714405489/article/details/100931236