The behavior model of reading notes in Gof design mode (bottom)

Source: Internet
Author: User

Background

The behavior model mainly controls the behavior between classes. This is very important for decoupling, how to divide the classes of their respective roles, grasp the granularity, control their message flow is very important, these models are sometimes more strange. Take it slowly.

Introduction to the Model

Let's look at 6 patterns of behavioral design.

1. MEMENTO (memo) 1.1 Intentions

captures the internal state of an object without compromising encapsulation, and saves the state outside that object. The object can then be restored to its previously saved state.

1.2 Applicability

Use the memo mode in the following situations:

    • You must save the (partial) state of an object at a certain point in time so that it can revert back to its previous state if needed later.
    • If one uses interfaces to get these states directly from other objects, it exposes the implementation details of the object and destroys the encapsulation of the object.
1.3 Structure diagram

1.4 Effects

The memo mode has some of the following effects:

    1. Keep the envelope boundary use memos to avoid exposing information that should only be managed by the original and that must be stored outside of the original sender. This mode masks potentially complex orignator internal information against other objects, preserving the encapsulation boundary.
    2. It simplifies the original generator in other packaging-preserving designs, and originator is responsible for maintaining the internal state version requested by the customer. This gives all the storage management responsibility to originator. Having customers manage the status of their requests simplifies originator and allows customers to end their work without notifying the sender.
    3. The use of memos can be costly if the source must copy and store a large amount of information when generating a memo, or if the customer creates a memo and restores the status of the generator very frequently, it can cause a very high overhead. This pattern may not be appropriate unless the cost of encapsulating and recovering the originator state is small. See the discussion on incremental changes in the implementation section.
    4. Defining narrow interfaces and wide interfaces can be difficult in some languages to guarantee that only the status of a memo can be accessed by the original.
    5. The potential cost manager for maintaining a memo is responsible for deleting the memos it maintains. However, the manager does not know how many states are in a memo. Therefore, when storing memos, a very small manager can generate a lot of storage overhead.
Attention

This pattern is simply to save a variable in a class. These variables are encapsulated. and then recover.

2. OBSERVER (Observer) 2.1 Intentions

Defines a one-to-many dependency between objects, and when an object's state changes, all objects that depend on it are notified and automatically updated.

2.2 Applicability

You can use observer mode in any of the following situations:

    • When an abstract model has two facets, one aspect depends on the other. The two are encapsulated in separate objects so that they can be individually changed and reused.
    • When a change to an object needs to change other objects at the same time, it is not known how many objects need to be changed.
    • When an object must notify other objects, it cannot assume that other objects are who. In other words, you don't want these
      The object is tightly coupled.
2.3 Structure diagram

2.4 Effects

Observer mode allows you to change the target and observer independently. You can reuse the target object individually without having to reuse its observers at the same time, and vice versa. It also allows you to increase the observer without altering the target and other observers. Here are some other advantages and disadvantages of the Observer pattern:

    1. Abstract coupling between the target and the observer one goal is to know only that it has a series of observers, each conforming to the simple interface of the abstract observer class. The target does not know which specific class any observer belongs to. This coupling between the target and the observer is abstract and minimal. Because the target and the observer are not tightly coupled, they can belong to different levels of abstraction in a system. A target object at a lower level can communicate with a higher-ranking observer and notify it, thus preserving the integrity of the system hierarchy. If the target is mixed with the observer, the resulting object will either traverse two levels (in violation of the hierarchy) or must be placed in one layer of the two layers (which may damage the hierarchy abstraction).
    2. Support for broadcast communication unlike the usual request, the notification sent by the target does not need to specify its recipient. Notifications are automatically broadcast to all relevant objects that have been registered with the target object. The target object does not care how many objects are interested in itself; its sole responsibility is to inform its observers. This gives you the freedom to add and remove observers at any time. Processing or ignoring a notification depends on the observer.
    3. Unexpected updates because an observer does not know the existence of other observers, it may be ignorant of the ultimate cost of changing the target. A seemingly harmless operation on the target may result in a series of updates to the observer and those objects that depend on those observers. In addition, if the dependency criterion is defined or poorly maintained, it often causes incorrect updates, which are often difficult to capture. The simple update protocol does not provide specific details about what has changed in the target, which makes the above problem more serious. If no other protocol helps observers find out what has changed, they may be forced to try to reduce the change.
2.5 Note

This is very important for decoupling. In fact, we want to understand the broad sense of the notice, from the root is the communication. Syntactically, an if statement decides who to notify. How to handle it. Broadcasting in the Android system is a typical observer pattern, and I think ContentProvider is the same. But he decided to get that component. This is still a newsletter.

3. State (status) 3.1 intent

Allows an object to change its behavior when its internal state changes. The object appears to have modified its class.

3.2 Applicability

The state mode can be used in either of the following cases:

    • The behavior of an object depends on its state, and it must change its behavior according to state at run time.
    • An operation contains large, multi-branched conditional statements that depend on the state of the object. This state is usually represented by one or more enumeration constants. Typically, there are multiple operations that contain this same conditional structure. The state mode places each conditional branch into a separate class. This allows you to use the object's state as an object based on the object's own situation, which can vary independently of other objects.
3.3 Structure diagram

3.4 Effects

The state mode has some of the following effects:

    1. It will localize the behavior related to a particular state and separate the behavior of different states from the state mode to put all behaviors related to a particular state into an object. Because all of the state-related code exists in a class, it is easy to add new states and transformations by defining new subclasses. Another approach is to use data values to define the internal state and have the context operation explicitly examine the data. However, this will cause the entire context implementation to be spread across the seemingly similar conditional or case statements. Adding a new state may require several actions to be changed, which makes maintenance more complicated. The state mode avoids this problem, but it may introduce another problem because it distributes the behavior of different states across the same class. This increases the number of subclasses, which is less compact than the implementation of a single class. However, this distribution is actually better if there are many states, otherwise a huge conditional statement is required. Like a long process, huge conditional statements are unwelcome. They form a whole block and make the code less clear, which makes it difficult to modify and extend. The state mode provides a better way to organize code that is related to a particular status. The logic that determines the state transition is not in a single block of if or switch statements, but rather is distributed between the states subclasses. By encapsulating each state transition and action into a class, the focus is raised from the execution state to the state of the entire object. This will make the code structured and make its intentions clearer.
    2. It makes the state transition explicit when an object defines the current state only with internal data values, its state is only represented by the assignment of some variables, which is not clear enough. The introduction of separate objects for different states makes the conversion more explicit. Also, the state object guarantees that the context does not have internal state inconsistencies, because from a context point of view, the status transition is atomic-simply rebind a variable (that is, the CONTEXTT state object variable) without assigning a value to multiple variables
    3. The state object can be shared if the States object does not have an instance variable-that is, the status they represent is completely encoded with their type-then each context object can share a single, one. When states are shared in this way, they must be lightweight objects with no internal state, only behavior (see flyweight).
3.5 Note

There's something here. Use different classes depending on the situation. This is for encapsulation, and finding the essence is that judgment if or switch.

4. Strategy (strategy) 4.1 intent

Define a series of algorithms, encapsulate them one by one, and make them interchangeable with each other. This mode allows the algorithm to be independent of the customers who use it.

4.2 Applicability

Use strategy mode when the following conditions are present

    • Many of the related classes are simply behavior-specific. Policy provides a way to configure a class with one behavior in multiple behaviors.
    • You need to use different variants of an algorithm. For example, you might define algorithms that reflect different spatial/temporal tradeoffs. When these variants are implemented as a class hierarchy of an algorithm, the policy mode can be used.
    • The algorithm uses data that the customer should not know about. You can use the policy mode to avoid exposing complex, algorithmic-related data structures.
    • A class defines a variety of behaviors, and these behaviors appear as multiple conditional statements in the operation of this class. The related conditional branches are moved into their respective strategy classes in place of these conditional statements.
4.3 Structure diagram

4.4 Effects

The strategy model has some of the following advantages and disadvantages:

  1. Correlation algorithm Series strategy class hierarchy defines a series of reusable algorithms or behaviors for the context. Inheritance helps to extract public functionality from these algorithms.
  2. One alternative to inherited method inheritance provides another way to support multiple algorithms or behaviors. You can generate a subclass of a context class directly, giving it different behavior. But this will make the behavior hard line into the context, and the implementation of the algorithm and the implementation of the context to mix, so that the context is difficult to understand, difficult to maintain and difficult to expand, and can not dynamically change the algorithm. Finally you get a bunch of related classes, the only difference between them is the algorithm or behavior they use. Encapsulating the algorithm in a separate strategy class allows you to change it independently of its context, making it easy to switch, easy to understand, and easy to extend.
  3. Elimination of some conditional statements the strategy pattern provides an alternative to selecting the desired behavior with a conditional statement. When different behaviors are stacked in a class, it is difficult to avoid using conditional statements to choose the appropriate behavior. These conditional statements are eliminated by encapsulating the behavior in a separate strategy class.
  4. The chosen strategy mode of implementation can provide different implementations of the same behavior. Customers can choose from different strategies based on different time/space tradeoffs.
  5. Customers must understand the different strategy this model has a potential disadvantage, is that a customer to choose a suitable strategy must know how these strategy are different. You may have to expose your customers to specific implementation issues at this point. Therefore, you need to use Strategy mode only when these different behavior variants are related to customer behavior.
  6. The communication overhead between the strategy and the context, regardless of whether the algorithms implemented by each concretstrategy are simple or complex, share strategy defined interfaces. Therefore, it is possible that some concretstrategy will not use all of the information passed to them through this interface; simple concretstrategy may not be using any of them! This means that sometimes the context creates and initializes some parameters that will never be used. If there is such a problem, there will need to be more tightly coupled between the strategy and the context.
  7. Increase the number of objects strategy increases the number of objects in an app. Sometimes you can strategy the real
    This overhead is now reduced for stateless objects that can be shared by each context. Any remaining state is maintained by the context. The context passes this state through a request to the Strategy object. Shared strategy should not maintain state between invocations. This method is described in more detail in the flyweight model.
4.5 Note

There is a class to handle, making the logic clear. Decoupling. or the switch or if statement

5. Template Method 5.1 Intent

Defines the skeleton of an algorithm in an operation, and delays some steps into subclasses. Templatemethod allows subclasses to redefine some specific steps of the algorithm without altering the structure of an algorithm.

5.2 Applicability

The template method applies to the following situations:

    • One-time implementation of an invariant part of the algorithm, and the variable behavior is left to subclass to achieve.
    • The public behavior in each subclass should be extracted and centralized into a common parent class to avoid code duplication. This is a good example of what Opdyke and Johnson described as "re-factoring to generalize." First identify the differences in the existing code and separate the differences into new operations. Finally, replace these different code with a template method that invokes these new operations.
    • Controls the subclass extension. The template method invokes the operation only at a specific point, so that only those points are allowed to be extended.
5.3 Structure diagram

5.4 Effects

A template method is a basic technique for code reuse. They are particularly important in class libraries, which extract public behavior from the class library.
The template method leads to a reverse control structure, which is sometimes called the "Hollywood rule," that is, "Don't look for us, we're looking for you." This refers to the operation of a parent class calling a subclass, not the other way around. The template method invokes the following types of operations:

    • Specific actions (concretclass or operations on the customer class).
    • Specific Abstraclass operations (that is, operations that are typically useful to child classes).
    • Primitive operations (that is, abstract operations).
    • Factory Method.
    • Hook operations, which provides the default behavior that subclasses can extend if necessary. One
      The hook operation is usually an empty operation in the default operation.
5.5 Note

This is simply the use of inherited syntax. Control of the necessary extensions or algorithms.

6. VISITOR (visitor) 6.1 Intentions

Represents an operation that acts on each element in an object structure. It allows you to define new actions that act on these elements without changing the class of each element.

6.2 Applicability

Use the visitor mode in the following situations:

    • An object structure contains many classes of objects that have different interfaces, and you want to implement some operations that depend on their specific classes for those objects.
    • You need to do many different and unrelated operations on objects in an object structure, and you want to avoid classes that let these actions "pollute" those objects. Visitorr allows you to centralize related operations into a class. When the object structure is shared by many applications, use Visitorr mode to have each app contain only the actions that need to be used.
    • Classes that define the structure of an object rarely change, but it is often necessary to define new operations on this structure. Changing the object structure class requires
6.3 Structure diagram

6.4 Effects

Here are some of the advantages and disadvantages of the visitor pattern:
1. The visitor pattern makes it easy to add new operator visitors, making it easier to increase the operations of components that rely on complex object structures. You can define a new action on an object structure simply by adding a new visitor. Conversely, if each function is scattered over multiple classes, each class must be modified when defining the new operation.
2. The visitor concentrates the related actions and separates unrelated actions related behavior is not distributed across the classes that define the structure of the object, but is concentrated in one visitor. Unrelated behaviors are placed in their respective visitor subclasses. This simplifies both the classes of these elements and simplifies the algorithms defined in these audiences. All of the data structures associated with its algorithm can be hidden from the visitor.
3. Adding new Concreteelement classes is difficult visitor mode makes it difficult to add new subclass of E lement. Each addition of a new concreteelement adds a new abstraction to the visitor and implements the appropriate action in each of the Concretvisitor classes. Sometimes it is possible to provide a default implementation in visitor, which can be inherited by most concretevisitor, but this is not so much a rule as an exception. So the key question to consider when applying the visitor pattern is which part of the system changes frequently, the algorithm that works on the structure of the object, or the class that makes up the individual objects of the structure. If new concretelement classes are always added, the Vistor class hierarchy becomes difficult to maintain. In this case, these operations are defined directly in the class that makes up the structure
might be easier. If the element class hierarchy is stable, and you continually increase the manipulation of the modified algorithm, the visitor pattern can help you manage these changes.
4. Accessing an iterator through the class hierarchy (see iterator) can traverse the entire object structure and access the objects by invoking specific operations on the node object. However, iterators cannot manipulate object structures that have different element types.
5. Cumulative status It may accumulate state when a visitor accesses each element in the object structure. If there is no visitor, this state is passed as an additional parameter to the traversal operation, or to a global variable.
6. The break encapsulation accessor method assumes that the Concreteelement interface is powerful enough to allow visitors to do their work. As a result, this pattern often forces you to provide a public operation that accesses the internal state of an element, which can damage its encapsulation.

Attention

In fact, it's very close to the observer pattern, just a matter of deciding which one is acceptable.

Analysis

In fact, each pattern is supported by syntax, the key to know the specific grammatical essence, all of the relational model is to reduce the degree of coupling in each class. Be sure to think about the essence.

The behavior model of reading notes in Gof design mode (bottom)

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.