11 types are commonly used in 23 design modes

Source: Internet
Author: User
Tags types of functions

Http://35java.com/zhibo/forum.php? MoD = viewthread & tid = 140 & extra = Page % 3d3

Design Pattern: <Design Pattern> there are 23 Design Patterns in Java.

I. design pattern is one of the most important courses. It is called jiuyang Zhenjing in the software field. design pattern is a set of frequently used ones that most people know and are classified,CodeTo sum up, the design pattern is used to make code reusable and make it easier for others to understand and ensure code reliability.

II. The most common reason for learning the design model is that we can use it:

1. Reuse solutions-avoid repeating the mistakes of our predecessors and benefiting from others' experience. You don't need to design a solution for problems that will always repeat.

2. Determine general terms-the design model provides a common benchmark in the project analysis and design phases.

Iii. design patterns generally follow these principles:

1. Programming by interface.

2. Use combinations instead of inheritance.

3. Identify and encapsulate the changes.

The following is a specific design pattern:

(1) Factory Model <factoty>

Definition: Replace the constructor and the New Keyword with a method to hide object creation.

Problem solved: it is used to solve the problem that there are too many ways to generate one by one, which is prone to changes, or where the parent class and the class are easy to replace. The factory mode is equivalent to creating a new instance object. The factory mode makes it unnecessary for us to consider how a specific class is implemented.ProgramScalability, reducing coupling.

(2) Singleton mode <Singleton>

Definition: A class can only create one object in a Java virtual machine.

The Singleton mode can be constructed in either of the following ways:

A: The Global Singleton instance is created when it is used for the first time.

B: Hungry: A Global Singleton instance is created when the class is loaded.

The Singleton mode must meet the following four conditions:

1. The Singleton class must have a private constructor.

2. the instance of the singleton class must be global and modified using private static.

3. You must provide an open object creation method.

4. The put method must be public, static, and synchronized. Public synchronized static XXX ();

Where used: It is used when only one class instance can be created.

(3) facade mode <facade>

Definition: defines a high-level interface to implement interaction between all sub-classes. This interface integrates the classes of all sub-systems.

<Written Statement: provides a consistent interface for a group of interfaces in the subsystem. The facade mode defines a high-level interface, which makes the subsystem easier to use.>

Solution: There are many sub-interfaces, complex calls, and many internal interactions.

(4) Strategy Mode <strategy>

Definition: defines a seriesAlgorithmAnd encapsulate them so that they can be replaced. The policy mode enables the algorithm to change independently of the customers who use it.

Solution: a specific solution can be implemented in many ways.

Applicable situations:

A: if there are many classes in a system, and the difference between them is their behavior, you can use the policy mode to dynamically let an object select a behavior among many behaviors.

B: If a system needs to dynamically select one of several algorithms, these algorithms can be packaged into specific algorithm classes. These algorithms are subclasses of an abstract algorithm class. In other words, these algorithms have a unified interface. Due to the polymorphism principle, the client can choose to use any specific class algorithm and only hold one data type as the object of the abstract algorithm class.

(5) template mode <template>

Definition: defines a series of skeleton in the operation, and delays some operation steps to the subclass. Define the process for the parent class and implement the Child class.

Solve the problem: it mainly solves the repeated problem of code or process between sub-classes.

Advantages:

1: The Inheritance method is used to define the algorithm framework in the base class, and declare the variable part of the algorithm as overwritable, which is used by a specific subclass, in this way, different functions can be completed using the same framework, which is more efficient than the policy mode and simpler.

2: The subclass can redefine certain steps of an algorithm without changing the structure of an algorithm.

Structure of the template mode:

1>: abstractclass class defines one or more abstract methods for specific subclasses to implement them. In addition, it also implements this template method to define an algorithm skeleton, this template method not only calls the preceding abstract method, but also calls other operations as long as it can fulfill its mission.

2>: concreteclass (specific class): implements the abstract methods in the parent class to complete the steps related to the specific subclass in the algorithm.

Applicability:

1>: implement the unchanged part of an algorithm at a time and leave the variable behavior to the subclass for implementation.

2>: Public behaviors in each subclass should be extracted and concentrated into a public parent class to avoid code duplication. In fact, this is a good coding habit.

3>: Controls subclass extension. The template method can only call operations at specific points, so that only these points can be extended.

If you do not want to subclass the framework of your template method definition, you can do this in two ways:

1>: do not show your template method in the API.

2>: Set your template method to final.

(6) Adapter mode <adapter> (incompatible)

Example in life: transformer.

Definition: converts an interface of a class to another interface that the customer wants, so that two originally incompatible interfaces can work normally together.

In the example of the update method of the queryrun class of butil, if two parameters are provided and you want to convert them into three parameters, the adapter mode is used and the adapter mode is used, the first is the class adapter and the second is the Object Adapter, but considering the conditions observed in the design pattern:

A: programming by interface;

B: use combinations instead of inheritance.

C: Find the changes and encapsulate them.

So we use the Object Adapter.

Solution: a class or interface with similar functions already exists, but the method signature is different.

(7) Observer mode <observer> (1: dependency; 2: one-to-many)

Definition: defines a one-to-many relationship between an object. When the State of an object changes, all objects dependent on it are notified and updated automatically.

<Provides a synchronous communication method for associated objects to keep an object synchronized with other objects dependent on it>.

Solution: resolve mutual notifications of dependencies between multiple objects.

Intention: 1: When changing an object, you need to change other objects at the same time without knowing how many objects need to be changed.

2: When an object must notify other objects, it cannot assume who the other objects are. In other words, you do not want these objects to be tightly coupled.

Advantages and disadvantages:

1: synchronous communication between objects

2: one or more associated objects can be notified at the same time.

3: The relationships between objects are loosely coupled and depend on each other.

(8) Abstract Factory Model <abstractfactory> examples: Clothes, trousers, and shoes. They can be Adi's or Nike's .... And so on.

Definition: provides an interface for creating a series of related or mutually dependent objects without specifying their specific classes.

The reason is that it can completely separate the implementation classes from their generation process.

Purpose:

* A system must be independent of the creation, combination, and representation of its products.

* A system must be configured by one of multiple product generations.

* When you want to emphasize the design of a series of related product objects for joint use.

* When you provide a product class library, you only want to display their interfaces instead of implementations.

Abstract Factory is responsible for managing sub-factory objects. Sub-factory objects generate a specific type of product objects.

(9) status mode <State> (status determines behavior)

Status mode: Live instances: Red, green, and lights.

I. Definitions: different states and actions; or, each State has a corresponding action.

In layman's terms, a single State is an action, and different states have different actions.

Ii. When to use:

The State mode is usually used in actual use. It is suitable for "state switching ".

Because we often use if elseif else for status switching, if the status is determined to appear repeatedly, we need to think about whether the State mode can be used.

Iii. solution: the logic is not complex and cannot be solved. It cannot solve unknown states.

Solve the problem

1) the behavior of an object depends on its state, and it must change its behavior according to its state at runtime.

2) An operation contains a large number of multi-branch condition statements, and these branches depend on the state of the object.

Iv. Disadvantages

Each status corresponds to a specific status class, which disperses the whole and the logic is not clear.

V. Advantages

The introduction of the state mode removes the complicated and long logic judgment statements in the code.

In addition, a specific State role encapsulates the specific state and its corresponding behavior, which makes it easier to add a new state.

(10) decorator mode <decorator>: Examples in life: paint walls.

Definition: dynamically add some additional responsibilities to an object. To add a function,

The decorator mode is more flexible than the subclass generation mode.

In other words, without changing a classSource codeWithout inheritance and implementation, some additional functions can be dynamically added.

Solve the problem: an object needs to dynamically add attributes or blame

Applicability:

* Add roles to a single object dynamically and transparently without affecting other objects.

* Handle unrecoverable responsibilities.

* When the subclass generation method cannot be used for expansion. One case is that there may be a large number of independent extensions. To support each combination, a large number of subclasses will be generated, resulting in explosive growth of the number of subclasses.

Another scenario is that the class definition is hidden, or the class definition cannot be used to generate a subclass.

Why decorator?

We can usually use inheritance to Expand functions. If there are many types of functions to be extended, many sub-classes will be generated to increase the complexity of the system. At the same time, when using inheritance to implement function expansion, we must be able to foresee these extended functions. These functions are determined at compilation and static.

The reason for using decorator is: These functions need to be dynamically determined by the user to join the method and timing. decorator provides the "Plug and Play" method, during which to decide when to add the function.

How to use it?

As an example of piling in the adapter, there are two types in the adapter: Square Pile round pile. The adapter mode shows how to use these two classes comprehensively. In the decorator mode, we want to add some additional features when piling, such as digging holes and dingtalk boards on the piles. We don't care how to use two unrelated classes.

Advantages:

1) more flexibility than inheritance

2) use different decorative combinations to create combinations of different behaviors

3) the number of required classes is reduced.

Disadvantages:

1) flexibility brings about relatively large errors

2) generating more objects makes it difficult to identify errors

(11) combination mode <composite> for example, there is a set in the connection, and the map is the arraylisthashmap.

Example: combine various tree menus.

Definition: Organizes objects in a tree structure to form a "part-whole" hierarchy,

Make the client consistent with the use of a single object and a composite object.

Solution: tree data structure solution.

Applicability:

* You want to represent the part of the object-the overall hierarchy.

* If you want to ignore the differences between a composite object and a single object, you will use all objects in the composite structure in a unified manner.

Advantages and disadvantages of the composite mode and its applicability:

1) Advantages: Make the client simple to call. The client can use a combination structure or a single object in it, and the user does not have to deal with a single object or the entire combination structure, the client code is simplified.

2) Disadvantages: I think the leaf class should not implement component at all. It should basically only use a display function and cannot perform other operations such as adding or deleting, misoperations may occur if component is implemented.

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.