Summary of Design Patterns

Source: Internet
Author: User

First, the content of the outline

    1. Design Pattern Concepts
    2. Design Pattern Classification
    3. Design pattern Principles
    4. Single-Case mode
    5. Multi-instance Mode
    6. Factory mode
    7. Proxy mode
    8. Prototype mode

Ii. Specific Content

    1. Design Pattern Concepts

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 make code production truly engineering; Design patterns are the cornerstone of software engineering, like the structure of a building.

The root cause of advocating the use of design patterns is code reuse, which increases maintainability.

    1. Design Pattern Classification

The design pattern is divided into three types, a total of 23 kinds.

Creation mode (5): Singleton mode, abstract Factory mode, builder mode, Factory mode, prototype mode.

Structural mode (7): Adapter mode, bridge mode, decoration mode, combination mode, appearance mode, enjoy meta mode, proxy mode.

Behavioral mode (11): Template method mode, command mode, iterator mode, observer mode, Mediator mode, Memo mode, interpreter mode, state mode, policy mode, responsibility chain mode, visitor mode.

    1. Design pattern Principles

Why should we advocate "Design pattern?" The root cause is for code reuse, which increases maintainability. So how do you implement code reuse?

There are several principles for object orientation:

Single Duty principle (Responsiblity Principle SRP)

Open Closed PRINCIPLE,OCP),

The principle of substitution on the Richter scale (Liskov Substitution PRINCIPLE,LSP),

Dependency reversal principle (Dependency inversion Principle,dip),

Interface Isolation principle (Interface segregation principle,isp), synthesis/aggregation multiplexing principle (composite/aggregate reuse principle,carp), minimum knowledge principle (Principle of Least Knowledge,plk, also known as Dimitri Law). The opening and closing principle has the idealistic color, it is the object-oriented design ultimate goal. The other several, can be regarded as the opening and closing principle of the implementation method.

The design pattern is the realization of these principles, so as to achieve code reuse, increase maintainability.

    1. Single-Case mode

Concept

In mathematics and logic, Singleton is defined as "a set with and only one element".

The initial definition of the singleton pattern appears in design mode (Eddisonvis, 1994): "Guarantees that a class has only one instance, and provides a global access point to access it." ”

The singleton schema definition in Java: "A class has and only one instance, and self-instantiation is provided to the system as a whole." ”

We can understand that a class has only one instance and provides a global access point to access it.

Applicability

When a class can have only one instance and the customer can access it from a well-known access point.

When this unique instance should be extensible by subclasses, and the customer should be able to use an extended instance without changing the code.

The singleton mode has the following characteristics:

1, the Singleton class can have only one instance.

2, the Singleton class must create its own unique instance.

3. The Singleton class must provide this instance to all other objects.

The advantages of the singleton pattern are:

Classes are instantiated only once, saving resources, reducing overhead, and increasing speed

Single-Case Pattern classification

There are two modes of creating a singleton, one is the A Hungry man mode, the other is the lazy mode, and the specific code is as follows:

/**
* Single case mode A hungry man mode
* @author <WPDA
* Application: Only need one is enough
* Role: To ensure that an instance of the entire program has and only one
*/
public class Starving {
1. Privatize the construction method and do not allow external direct creation of objects
Private Starving () {
}
2. Create a unique instance of a class
private static Starving instance = new starving ();
Provides a way to get an instance
It is important to note that this method belongs to the object, not the class method.
Public Starving getinstance () {
return instance;
//}
3. Provide a static member method for obtaining the private class of the instance
public static Starving getinstance () {
return instance;

}
}

/**
* Singleton mode lazy mode
* @author Administrator
*
*/
public class Lazy {
Privatization of construction methods, creation of objects without sequential external direct
Private Lazy () {
}
2. Declaring a unique instance of a class
private static Lazy instance;
3. Provide a method for obtaining an instance
public static Lazy getinstance () {
if (instance = = null) {
Instance = new Lazy ();
}
return instance;
}
}

A) A hungry man mode is characterized by the slow loading of classes, but the speed of the runtime to get objects faster, a hungry man-style is thread-safe, at the same time as the class creation has created a static object for the system to use, not change later.

b) Lazy mode is characterized by the faster loading of classes, but the speed of getting objects at run time is slow, the thread is not safe, lazy-type if you create an instance object without adding synchronized, the object's access is not thread-safe.

So we recommend that you use a hungry man mode.

Key Benefits:

1. Provides controlled access to the unique instance.

2, because there is only one object in the system memory, so it can save system resources, for some of the objects need to be created and destroyed frequently the singleton pattern can undoubtedly improve the performance of the system.

3. Allow a variable number of instances.

Main disadvantages:

1, because there is no abstraction layer in the simple interest mode, the expansion of the Singleton class has great difficulty.

2, the single-case category of excessive responsibility, to a certain extent, contrary to the "single principle of responsibility."

3, abuse of a single case will bring some negative problems, such as to save resources to the database connection pool object design as a singleton class, may cause the sharing connection pool object too many programs and a connection pool overflow, if the instantiated object is not exploited for a long time, the system will be considered as garbage, which will result in the loss of object state.

    1. Multi-instance Mode

One, the singleton mode and the multi-example mode description:

1). The singleton mode and the multi-instance mode belong to the object mode.

2). The singleton mode object has only one copy of the whole system, and multiple instances can have multiple cases.

3). None of them provide a construction method, that is, the construction method is private.

4). The schematic diagram of the singleton mode and the multi-sample mode is as follows:

Definition of a multiple-instance pattern:

As an object's creation mode, multiple instances of a multi-instance pattern can have multiple examples, and multiple classes must create, manage, and provide their own instances to the outside world.

Features of the multi-case model:

The so-called multi-case pattern (Multiton pattern) is actually a natural generalization of the singleton pattern. As an object creation mode, multiple cases or multiple classes have the following characteristics:

(1) Multiple instances of a class can have more than one instance

(2) Multiple cases must create and manage their own instances, and provide their own instances to the outside world.

(3) According to whether there are instances of the upper limit is divided into: there are upper limit of multiple cases and no upper limit multi-class.

    1. Factory mode

Concept

Defines an interface for creating objects, letting subclasses decide which class to instantiate. The Factory Method defers the instantiation of a class to its subclasses.

Applicability

When a class does not know the class of the object it must create.

When a class wants to specify the object it creates by its subclasses.

When a class delegates the responsibility of creating an object to one of several helper subclasses, and you want to set which helper subclass is the agent this information is localized.

Intent: Define an interface that creates an object, letting its subclasses decide which factory class to instantiate, and the factory pattern to defer its creation to subclasses.

Main Solution: The main solution to the problem of interface selection.

when to use: we explicitly plan to create different instances under different conditions.

How to solve: let its sub-class implement the Factory interface, return is also an abstract product.

Key code: The creation process executes in its subclasses.

Application Example: 1, you need a car, you can pick up directly from the factory, without having to control how the car is done, and the specific implementation of the car. 2, Hibernate Exchange database only need to change dialect and drive.

Pros: 1, a caller wants to create an object, just know its name. 2, high scalability, if you want to add a product, as long as the expansion of a factory class can be. 3, the specific implementation of shielding products, the caller only care about the interface of the product.

disadvantage: Each time you add a product, you need to add a specific class and object to implement the factory, so that the number of classes in the system multiplied, to a certain extent, increase the complexity of the system, but also increase the system specific class dependency. That's not a good thing.

usage Scenario: 1, Logger: Records may be logged to local hard disk, system events, remote server, etc., the user can choose where to log logs. 2, database access, when the user is not aware of the last system to use which type of database, and the database may change. 3, design a connection server framework, requires three protocols, "POP3", "IMAP", "HTTP", you can use these three as product classes, together to implement an interface.

Note: as a way to create a class pattern, you can use the factory method pattern in any place where complex objects need to be generated. One thing to keep in mind is that complex objects are suitable for Factory mode, and simple objects, especially those that can be created only through new, do not need to use Factory mode. If you use Factory mode, you need to introduce a factory class that increases the complexity of the system.

    1. Proxy mode

Concept

Provides a proxy for other objects to control access to this object.

Applicability

Use the proxy mode when you need to replace a simple pointer with a more general and complex object pointer. Here are some common scenarios where you can use the proxy mode:

Remote proxies provide local representation of an object in different address spaces.

Virtual proxies create expensive objects as needed.

The protection agent (Protection proxy) Controls access to the original object. The protection agent is used when the object should have different access rights.

Smart Reference replaces a simple pointer that performs some additional operations when accessing an object. Typical uses of it include:

A reference count that points to the actual object so that it can be automatically freed (also known as smartpointers) when there is no reference to the object.

When a persistent object is referenced for the first time, it is loaded into memory.

Before accessing an actual object, check to see if it has been locked to ensure that other objects cannot change it.

1. Initial knowledge of Agent mode

Everyone in life must have encountered such a situation: for example, I want to buy a towel, it may be clean lascar, that the general People's words I should not go to clean lascar factory directly to buy it, but we in the Jie Li Ya store or what supermarket ah, these places to buy, these places is actually Jie Li ya towel agent. This is actually very similar to the proxy pattern in our oo.

An IT person, the Internet should be a regular thing, then there will always be such a situation, open a Web page, the text appears first, and those relatively large resources, such as the case of the film to be displayed, this is why?? In fact, this is the proxy mode.

2. A simple example of proxy mode

Just say the example of the towel above, there will be the following class diagram:

3. The meaning of proxy mode

Where does the agency model benefit??

Let's talk about the three roles in proxy mode.

  abstract Role: a common interface for declaring real objects and proxy objects.
  Proxy Role: the Proxy object role contains a reference to the real object, allowing you to manipulate the real object while the proxy object provides the same interface as the real object to replace the real object at any moment. At the same time, the proxy object can attach other actions when performing the real object operation, which is equivalent to encapsulating the real object.
  Real role: the real object represented by the proxy role is the object we end up referencing.

One of the benefits of proxy mode is to provide a unified interface method to the external, while the proxy class implements the additional operation behavior of the real class in the interface, so that the system can be extended without affecting the external invocation. That is, I want to modify the actual role of the operation, try not to modify him, but outside in the "package" layer of additional behavior, that is, the proxy class. For example: interface A has an interface method operator (), the real role: Reala Implement Interface A, you must implement the interface method operator (). Client clients call interface A's connection method operator (). Now that the new demand is coming, we need to modify the operation behavior of the operator () in Reala. What do we do? If you modify the Reala will affect the stability of the original system, but also to re-test. This is required for the proxy class to implement additional behavior actions. Create the proxy Proxya implement interface A, and inject the real object Reala in. Proxya implements the interface method operator (), plus additional behavior can be added, and then invoke the real object's operator (). Thus achieved "to modify the closure, open to expansion", to ensure the stability of the system. We see that the client call is still the interface method operator () of interface A, except that the instance becomes the Proxya class. This means that the proxy mode implements the OCP principle.

4. When to use proxy mode

When the objects we need to use are complex or take a long time to construct, then we can use proxy mode. For example, if building an object is time consuming and computer resources, Proxy mode allows us to control this situation until we need to use the actual object. A proxy usually contains the same method as the object that will be used, and once the object is started, these methods are passed to the actual object by proxy. Some scenarios in which you can use proxy mode:

An object, such as a large image, takes a long time to load.

A calculated result that takes a long time to complete and needs to show intermediate results during its calculation

An object that exists on a remote computer requires a long time to load the remote object over the network, especially during periods of network transmission.

An object has limited access rights, and proxy mode can verify the user's permissions

Proxy mode can also be used to distinguish between an object instance request and the actual access, for example: in the program initialization process may establish multiple objects, but not all immediately use, proxy mode can be loaded into the real object required. This is a program that needs to load and display a very large image, when the program starts, it must determine the image to be displayed, but the actual image can only be displayed when fully loaded! In this case, we can use the proxy mode.

    1. Prototype mode

Concept

Use the prototype instance to specify the kind of object to create and create a new object by copying the prototypes.

Applicability

When the class to be instantiated is specified at run time, for example, by dynamic loading, or to avoid creating a factory class hierarchy that is parallel to the product class hierarchy, or when an instance of a class can have only one of several different state combinations. Building the corresponding number of prototypes and cloning them may be more convenient than manually instantiating the class each time you use the appropriate state.

When we talk about prototype patterns, we have to differentiate between two concepts: deep copy, shallow copy.

Shallow copy: Use a known instance to assign a value to the member variable of the newly created instance, which is called a shallow copy.

Deep copy: When a copy of a class is constructed, the value of all non-reference member variables of the object is not only copied, but also a new instance is created for the member variable of the reference type and initialized to the formal parameter instance value.

Advantages

1, if the creation of new objects is more complex, you can use the prototype model to simplify the creation of objects, but also to improve efficiency.

2. You can use deep clones to persist the state of an object.

3. Prototype mode provides a simplified creation structure.

Disadvantages

1, in the implementation of deep cloning may require more complex code.

2, the need for each class to be equipped with a cloning method, and this cloning method needs to consider the function of the class, which is not very difficult for the new class, but the transformation of the existing class is not necessarily an easy thing, must modify its source code, contrary to the "open and closed principle."

Summarize

1. Prototype mode hides the complexity of creating objects from the customer. The customer only needs to know the type of object to be created, and then, with the request, it can get a new object that is identical to that object without needing to know the exact creation process.

2, clone is divided into shallow clone and deep clone two kinds.

3, although we can use the prototype model to obtain a new object, but sometimes the replication of objects can be quite complex, such as deep cloning.

Summary of Design 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: 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.