Design Mode Reading Notes-behavior mode

Source: Internet
Author: User

Design Mode Reading Notes-behavior mode
1. chain of responsibility chain

Usage: · Multiple objects can process one request, and the specific object that processes the request must be automatically determined at runtime.
· The object set that can process a request should be dynamically specified

Principle: each object on the chain has the same request processing interface as the successor interface on the access chain.
Start from the first object on the chain, either process it in person or forward it to the next candidate in the chain.
The client who submits the request does not know which object will process the request. The client who submits the request does not directly reference the object that finally responds to the request.

Implementation: class HelpHandler /////// base class, maintenance chain parent node reference (successor)
{
HelpHandler (HelpHander * successor): _ successor (successor ){}
Virtual void HandleEvent (Event e)
{
_ Successor-> HandleEvent (e );
}
Private:
HelpHandler * _ successor;
};
Class Bottun: public HelpHandler
{
Bottun (HelpHandler * h): HelpHandler (h ){}
Void HandleEvent (Event e)
{
If (can deal with event)
{
Do some thing;
}
Else
{
HelpHandler: HandleEvent (e); // The next object to the chain
}
}
};
Class Dialog: public HelpHandler
{
Dialog (HelpHandler * h): HelpHandler (h ){}
Void HandleEvent (Event e)
{
If (can deal with event)
{
Do some thing;
}
Else
{
HelpHandler: HandleEvent (e); // The next object to the chain
}
}
};

App:
{
Dialog = new Dialog (0); // No node under it
Button = new Button (& dialog); // The next node on the chain
Button-> HandEvent (event); // the event may be processed by a dialog or button.
}


2. command

Use: 1. command to decouple the object that calls the operation from the object that knows how to implement the operation. (The receiver of the command is assembled when the command object is declared)
But what are the benefits? As an object, a command can provide its own execute method to execute itself, saving the switch? Or
The total entry (object) of the response command does not need to know all the functions provided by the user, nor need to identify the function that handles the command by yourself.
The command receiver may only provide some basic functions. to process each command, you need to sort and combine the basic functions so that you can put them in the command.
Implementation (using basic functions ).

2. The command is processed as an object. It has a certain declaration period and provides a possibility for rollback, as long as each command implements the UnExecute method.

3. You can combine multiple commands into a composite command (combination mode ).
4. It is easy to add commands without affecting existing classes.

Principle: encapsulate command into a class and provide the Execute method. At the same time, you may maintain a reference of the command receiver (registered when declaring the command), which is an object that provides specific actions.
You must consider whether the intelligence of a command is complete or directly transferred to the command receiver. There is a degree to be determined based on the situation.

Multiple commands can also be combined into one.

Implementation:
Class Command
{
Virtual void Execute () = 0;
};
Class OpenCommand: Command
{
OpenCommand (Application * a) :__ application (_ application ){}
Void Execute ()
{
_ Application-> AddDocument ();
}
Private:
Application * _ application;
};

App:
{
Application app; // The recipient of the command
Command * open = new OpenCommand (& app );
Open-> Execute ();
}


3. Interpreter

The interpreter and the combination are similar, and the combination will be used in the implementation. Their difference is that the combination focuses on expressing objects in a common way, even if
It is a group of objects and is expressed as an object.

The interpreter sets a voice for the clientAPP or user interface to solve specific problems. The interpreter tree (or list) is determined by translating this speech)
Each object in (a subclass that interprets a specific syntax ).

Compared with the combination mode, he first translated speech in one step and translated the language into sub-classes of each interpreter (build the number of syntaxes ). And the behavior of each subclass can also be different. For example, the string searches for "starting with what, ending with what, and containing what ..."
# A starts with a; $ a ends with a. % a contains.
You can define three subclasses and use the translation language: # ss $ B to search for strings starting with ss and ending with B.


4. Iterator

Motivation: provides a method to traverse an aggregate object without exposing its internal representation.
List iterator is an instance. We do not know how data is stored in the list.

This also supports multiple traversal and different traversal of the same aggregated object at the same time. You can use different iterators.
Provides a unified interface for traversal and aggregation.

Implementation:
Template <class Item>
Class Aggregate
{
Long count ();
Item & getitem (long index); // The actual aggregate object, which provides a method to obtain elements based on subscript, in this way, the iterator can not be declared as his friend.
Declaring the iterator as a friend of aggregation is also a method, but it damages the encapsulation of aggregation.
};

Class Iterator // abstract Iterator Interface
{
Virtual void first () = 0;
Virtual void next () = 0;
Virtual bool isDone () const = 0;
Virtual Item CurrentItem () const = 0;
};
Class ConceretIterator: public Iterator
{
ConceretIterator (const Aggregate & a): aggregate (a), _ current (0 ){}
Void first ()
{
_ Current = 0;
}
Void next ()
{
_ Current ++;
}
Bool isDone () const
{
_ Current = aggregate. count ();
}
Virtual Item CurrentItem () const
{
Return aggregate. getitem (_ current );
}
Private:
Long _ current;
Aggregate & aggregate;
};
The above is an external iterator, that is, the operation on the item is carried out in the external app, and the iterator only returns the item.
App:
{
ConceretIterator I (Aggregate );
For (I. first ();! I. IsDone (); I. next ()
{
Item & item = I. CurrentItem ();
}
}

You can also define the factory in aggregate and create the corresponding iterator through the factory method.★Because the factory usually uses new, the iterator can also package another proxy to release the iterator object.
IteratorProxy (CreateIterate (); IteratorProxy itself is the proxy mode of the iterator, while CreateIterate is the factory mode, which uses the new method.
In this case, the IteratorProxy overload-> and * methods are required to spit out the contained objects. Delete the new object from the factory in the IteratorProxy destructor.

There is also an internal iterator that handles object operations by yourself.
Class ListTraverser {
ListTraverser (Aggregate & a): iter (){}
Bool traverse ()
{
For (iter. first ();! Iter. IsDone (); iter. next ()
{
ProcessItem (iter. CurrentItem ());
}
}
Protected:
Virtual bool ProcessItem (const Item &); // The processing function of item
Private:
Iterator & iter; // you have an Iterator.
};


5. mediator intermediary

Intention: when a group of objects communicate in a complex way, the mutual dependency generated is confusing and hard to understand.
To define a behavior that is distributed across multiple classes, you do not want to generate too many child classes.
When a class references many other objects, the reusability decreases.
In this case, you can use an intermediary to hold and maintain a series of object interactions and coordinate the collaborative behavior of colleagues.

Principle: an intermediary is used to encapsulate a series of objects, so that each object does not need to be explicitly referenced, so that it is loosely coupled.

Implementation:
Class DialogDirector
{
Void changed () ///// external interface of the intermediary
{
_ OK. xxx ();
_ Cancel. xxx ();
If (_ fontlist changed)
{
Xxxx;
}
}
Private:
Button & _ OK; // maintain several colleagues and coordinate their work
Button & _ cancel;
ListBox & _ fontlist;
};

6. memento Memorandum

Purpose: Obtain the internal state of an object without compromising encapsulation, and save it outside of the object so that the original state of the object can be restored as needed.

Principle: The object in the Saved state is called the primary machine. The primary machine provides its own interface to generate its own memorandum object, and provides an interface for restoring the State to load the memorandum.
That is, the primary machine defines its own memorandum and provides the interface to return it. The application can get this memo and restore the data to the source when necessary.

Implementation:

Class OriginatorMemento // Memorandum
{
~ Originator ();
Private:
Firend class Originator;
OriginatorMemento ();
};

Class Originator // The primary machine
{
OriginatorMemento * CreateMemento ();
Void setMemento (OriginatorMemento & memento );
};

App
{
OriginatorMemento * _ state = Originator. CreateMemento ();
///////////////////////////////........

Originator. setMemento (_ state); // You can import the memorandum in this way.
}


In fact, it is like backing up data to a file in an encrypted way. How to back up and use data is a matter of the primary machine, and it is completely encapsulated.


7. observer

Intention: Define a one-to-multiple relationship between objects. When the status of an object changes, all objects dependent on it are notified and updated automatically.

Principle: The observer is an object that can hold the reference of the object to be observed. The observed object provides a registration method to register the objects that you want to observe to him.
All observers inherit from abstract interfaces.
When the observer changes, call the update method registered to the observer in sequence through its own ipvy interface, and pass it over, this allows the observer to perceive his changes.

Implementation:

Class Observer
{
Virtual void Update (Subject *) = 0;
};

Class ConceretObserver: public Observer
{
Void Update (Subject * s)
{
XXXXXXXXXXXXXXXX;
}
};

Class Subject
{
Void Register (Observer * o)
{
M_oberList-> push_back (o );
}
Void Notify ()
{
For (I = m_oberList.begin (); I! = M_oberList.end (); I ++)
{
(* I)-> Update (this );
}
}
Void Function () ///////// a specific Function of the target class. When the data changes, call Notify y to trigger his observer.
{
////////////
Notify ();
}
Private:
List M_oberList;
};

★In this case, when an operation involves multiple interdependent targets, the observer can be notified only after all the modifications to these targets are completed. In this case, a ChangeManager can be introduced, maintains the relationship between the target and the observer and the notification time.
In this case, changeManager is the Mediator mode between the observer and the target. ChangeManager is usually implemented using a single piece.

It is also possible that the observer only wants to observe the changes of a specific event. In this case, the observer can define the observation event he is interested in by registering the interface. It can save some invalid notifications.

8. state status

Intent: Allow an object to change its behavior when its internal state changes. The object looks like modifying its class.

Principle: Context defines the interface that the customer is interested in and maintains a reference to a specific State subclass, which corresponds to the current state of the Context.
Defines an interface through an abstract state to encapsulate behaviors related to a specific state of the context. Then, the behavior related to the context state is implemented through the specific state subclass.
Context delegates status-related requests to the current specific state subclass. Context can pass itself as a parameter to the State object that processes the request, and the State object can access context.
The client program calls the context interface.
Both context and the specific state subclass can determine which state is the successor of another state.

It will localize the behavior related to a specific State.


9. strategy

Purpose: define a series of algorithms, encapsulate them one by one, and they can replace each other. This allows algorithms to change independently of other customers.
For example, there can be many Text wrap algorithms, each of which is encapsulated into a policy.
Different algorithms can be used for different programs.

If the algorithm is directly implemented in the context, the context implementation and algorithm implementation will be mixed, but the context is difficult to maintain. The algorithm is hard-coded and cannot be dynamically changed.
If context is derived in this case, a bunch of related classes are obtained, and the only difference is the algorithm.

In this way, it is better to separate the implementation of the algorithm from the context, so that the context can switch the algorithm used by him.


Implementation: You can use strategy as the class template parameter to configure the class. However, you can select strategy during compilation, but you cannot select strategy during runtime.
Another method:

Class Context
{
Context (strategy * s): _ s (s ){}

Void dosomething () /////// the application implements a function.
{
_ S-> compose (); // call the abstract API of the Algorithm
}
Private:
Strategy * _ s;
};

Class strategy
{
Virtual void compose () = 0;
};

Class conceretStrategy1: public strategy
{
Void compose ()
{
XXXXXXXXXXXXXX;
}
};

Class conceretStrategy2: public strategy
{
Void compose ()
{
XXXXXXXXXXXXXX;
}
};

App
{
Context * s1Context = new Context (new conceretStrategy1 );
Context * s2Context = new Context (new conceretStrategy2 );

S1Context-> compose ();
}

10. template method

Purpose: Define the skeleton of an algorithm in an operation and delay some steps to the subclass. This allows subclass to redefine certain steps (or actions) of an algorithm without changing the structure of the algorithm ).

Implement the immutable part of an algorithm at one time, and leave the variable behavior to the subclass for implementation.

Implementation: The primitive operation for calling a template method can be defined as protected to ensure that it is called only by the template method. Primitive operations that must be redefined are defined as pure virtual functions.
The template method itself does not need to be redefined, so it is defined as a non-virtual function.

Class AbstractClass
{
Void TemplateMethod () //////// implement the skeleton of an algorithm, which uses the DoOperate () method that can be overloaded and is reloaded in its subclass; subclass uses the algorithm skeleton of the parent class to redefine its own operations.
{
XXXXXXXX;
DoOperate1 ();
XXXXXXXXXXXXX;
DoOperate2 ();
Xxxxxxxxxxx;
}
Virtual void DoOperate1 () = 0;
Virtual void DoOperate2 () = 0;
};

Class ConceretClass: public AbstractClass
{
Virtual void DoOperate1 ()
{
XXXXXXXXXXXXXXXX;
}
Virtual void DoOperate2 ()
{
XXXXXXXXXXX;
}
};
The template method is based on the inheritance technology and is not as flexible as strategy.

11. visitor

Intention: an operation that acts on each element in an object structure can define new operations on these elements without changing the element classes.
You need to perform a lot of irrelevant operations on the objects in an object structure, instead of interfering with each other.

Visitors make it easy to add operations that depend on the owner object. You only need to add a new visitor to define a new operation in the object structure.
Visitors can separate irrelevant operations in a centralized manner. So that the relevant operation behaviors are concentrated in the visitor rather than distributed in the object structure.
It is easy to add new operations.

He emphasizes the diversity and independence of operations.

Principle: Define an abstract visitor that identifies an interface for accessing object elements.
Use the specific conceretVisitor to inherit from the visitor.
Use abstract elements to define an interface that accepts visitors, such as Accept operations, with a visitor as the parameter.
The specific elements inherit from the abstract elements to implement the accept operation.

Implementation:
Class Equipment
{
Virtual int discountPrice ();
Virtual accept (EquipmentVisitor * v );
};

Class FloppyDisk: Equipment
{
Accept (EquipmentVisitor * v)
{
V. visitFloppyDisk (this); //////// the accept method of each specific Element object is implemented differently, using different methods in visitor, however, these methods are overloaded and have a unified interface prototype. That is
Each specific Element object can have multiple visitor, and multiple of them have a common abstract interface.
}
}
Class EquipmentVisitor
{
Virtual void visitFloppyDisk (FloppyDisk * f );
Virtual void visitBus (Bus * B );
};

Class InventoryVisitor: public EquipmentVisitor
{
Void visitFloppyDisk (FloppyDisk * f)
{
F-> Accumulate (); // calculate the inventory quantity of FloppyDisk
}
};

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.