33. Summary of design patterns-behavior patterns

Source: Internet
Author: User

Design Mode Summary

Iii. Behavior Model

1, Observer Mode

Defines a 1: N dependency between objects. When 1 changes, N will be notified.

Advantage: Use List to record this group of objects, and use foreach to call the object method as needed

Conclusion: The features are obvious and can be used in specific situations.

Class BOSS: Subject

{

Private ilist <observer> Observers = newlist <observer> ();

Private string action;

Public void attach (Observer observer) {observers. Add (observer );}

Public void detach (Observer observer) {observers. Remove (observer );}

Public voidnotify () {foreach (Observer o in observers) {o. Update ();}}

Public String subjectstate {get {returnaction;} set {Action = value ;}}

}

2, Template method

Define the skeleton of the algorithm and delay some steps to the subclass. Steps for restructuring the algorithm.

Advantage: it is convenient to reconstruct the algorithm steps.

Disadvantages: grasp the freedom of reconstruction and the complexity of reconstruction.

Conclusion: Different subclasses extended by the template method are used to implement different methods.

Classchild: Father

{

Public override void show2 ()

{

Base. show2 ();

Console. writeline ("viewing changes ");

}

}

3, Command mode

Encapsulate a request as an object to parameterize it with different requests.

Advantage: it is easier to design a command line-up

It is easier to log commands

Allow the recipient to decide whether to respond to the request

Supports undo and redo operations

Adding a new command does not affect other classes.

Disadvantages:

Conclusion: The structure features are obvious. The command is recorded first and then executed in a unified manner.

Publicclass waiter

{

Privateilist <command> order = new list <command> ();

Public void setorder (command) // sets the order

{

If (command. tostring () = "**") {console. writeline ("Chicken Wings are gone ");}

Else {order. Add (command );}

}

Public void cancelorder (command) // cancel the order {order. Remove (command );}

Public void Policy () // notification execution {foreach (command C in order) {C. excutecommand ();}}

}

4, Status Mode

When the internal state of an object changes, it is allowed to change its behavior. This object seems to have changed its class.

Advantage: when an object's behavior depends on its state, and it must change its behavior according to its state at runtime

Summary: When an operation contains a large multi-branch Condition Statement, the branch depends on the status. Need to make complex judgments

To some column classes that indicate different states.

The State mode only instantiates a class and changes its behavior based on the state of the object.

//Maintain a concretestateSubclass instance, which defines the current status

Class Context

{

Private state;

Public context (State state) // defines the initial state of Context

{This. State = State ;}

Public state // read/write the current state and set the new State

{

Get {return state ;}

Set {state = value; console. writeline ("current state:" + state. GetType (). Name );}

}

// Process the request and set the status

Public void request () {state. Handle (this );}

}

Classconcretestatea: State

{

Public override void handle (context)

{Context. State = newconcretestateb (); // set the next state}

}

5, Responsibility chain model

Connect the object to a chain and pass the request along the chain until an object processes it.

Advantage: Multiple objects have the opportunity to process requests, so as to avoid coupling between request senders and receivers.

Judge in Mode

Disadvantage: In the mode, each branch has a corresponding class.

Make sure there are class responsibilities.

Conclusion: The same as the status mode, it is a solution to complicated judgment.

However, the state mode is determined based on the object State and has only one object.

The responsibility chain mode is mainly determined by the processing class, otherwise it is passed to the next processing class.

//Request processing interface

Abstract class Handler

{

Protected handler successor;

Public void setsuccessor (handler successor) // set successor {This. Successor = successor ;}

Public abstract void handlerrequest (INT request); // The abstract method for processing the request

}

Class concretehandler1: Handler // You Have The Right to process data between 0 and 10.

{

Public override void handlerrequest (intrequest)

{

If (request> = 0 & request <10)

{Console. writeline ("{0} Processing request {1}", this. GetType (). Name, request );}

Else if (successor! = NULL) {successor. handlerrequest (request); // transfer to the next position}

}

}

6, Interpreter Mode

For a given language, define a representation of its syntax and define an interpreter that uses this representation.

To explain sentences in a language.

Advantage: traversal of all add methods is easy to expand and modify.

Disadvantage: difficult to maintain when many rules (methods) exist

Comprehensive: string matching, email identification, and phone number matching. Regular Expressions are an application of the interpreter mode.

Ilist <shortactexpression> List = new list <shortactexpression> ();

List. Add (New terminalexpression ());

List. Add (New nonterminalexpression ());

List. Add (New terminalexpression ());

List. Add (New terminalexpression ());

Foreach (abstractexpression exp in list) {exp. interpret (context );}

7, Intermediary Mode

Encapsulate a series of object interactions with an intermediary object. The intermediary makes the objects do not need to display mutual references, so that they are loosely coupled and can independently change the interaction between them.

Advantage: the complex communication is placed in the intermediary, and the objects that send and receive messages are reduced by coupling.

Adding Objects makes it easy to modify the logic.

Message sending and receiving, the object only needs to know the intermediary

Disadvantage: it is easy to use and misuse.

Well defined but complex communication

When there are many to many, it will be troublesome.

Conclusion: Do not rush to use the intermediary mode. The definition should be very clear. If there are many to many, first take the test

Whether the system design is reasonable

Class concretemediator: mediator//Intermediary type

{

Private concretecolleague1 colleague1;

Private concretecolleague2 colleague2;

Public concretecolleague1 colleague1 {set {colleague1 = value ;}}

Public concretecolleague2colleague2 {set {colleague2 = value ;}}

Public override void send (string message, colleague)

{

If (colleague = colleague1) {colleague2.notify (Message );}

Else {colleague1.y y (Message );}

}

}

8, Visitor Mode

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

Advantage: the coupling between the data structure and the operations acting on the structure is freed, so that the operation set can evolve freely.

Disadvantage: the most complicated design model

Summary: Applicable to systems with relatively stable data structures (rarely used ). Unless required or not.

It is difficult to add specific elements, but adding operations on components that depend on complex object structures will become quite simple.

Easy. You only need to add a new visitor to define a new operation in an object structure.

 

9, Rule Mode

Define a series of algorithms, encapsulate them one by one, and make them replaceable.

Advantage: algorithms are changed independently of customers who use them.

Summary: similar to a simple factory, but the factory class returns a class instance. Rule mode only returns methods.

Classcashcontext

{

Private cashsuper Cs;

Public cashcontext (cashsuper csuper) {This. cs = csuper ;}

Public double getresult (double Monty) {return CS. acceptcash (Monty );}

}

10, Memorandum Mode

Capture the internal state of an object without compromising encapsulation, and save the state outside the object. In order to restore the object to the original save state.

Advantage: without compromising encapsulation. Save this status outside of this object.

Summary: this function is generally used, but it can be recorded and restored without damaging the encapsulation.

It has obvious advantages and can be used to save data.

Classoriginator

{

Private string state; // saved attributes

Public String state {get {return state;} set {state = value ;}}

Public memento creatememento () // creates a memo to import and instantiate a memento object.

{Return (new memento (State ));}

Public void setmemento (memento) // restore memorandum {state = memento. State ;}

Public void show () {console. writeline ("state =" + state );}

}

11, Iterator Mode

Provides a method to access each element of an aggregate object sequentially without exposing the internal representation of the object.

Advantages: for example, foreach ().

Conclusion: currently, foreach is rarely used.

Ieumerator supports simple iterative interfaces for non-generic sets.

For example, foreach (string I in Str) {print I}

That is:

Ienumerator <string> E = Str. getenumerator ();

While (E. movenext ())

{

Printe. Current;

}

//Iterator abstract class

Abstract class iterator

{

Public abstract object first ();

Public abstract object next ();

Public abstract bool isdone ();

Public abstract object currentitem ();

}

 

 

 

 

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.