1. Chain of Responsibility
a) Structure:
Note: 1) Make multiple objects to handle requests, thereby avoiding coupling relationships between requesting senders and recipients. Connect these objects into a chain and deliver the request along this chain until there is an object to handle her.
b) Advantages:
i. Reduce the degree of coupling. Each object only needs to know how to forward the request. (Each object only needs to keep a subsequent reference)
II. Additional flexibility is provided in the distribution of posts, and the chains and responsibilities can be modified during operation. (By modifying the reunion, dynamic adjustment chain)
Iii. When there is no object to handle a request, the last object discards the request. (Provide default processing for requests)
c) Use the environment:
i. There are multiple objects to handle one request, which object processes the request, automatically determines at runtime.
Ii. You want to submit a request to a request in a plurality of objects without explicitly designating the recipient.
Iii. A collection of objects that can be handled should be dynamically specified.
d) Code instance:
Public Abstract Class Handler {
Protected handler success;
Public Abstract void handlerequest ();
}
Public Class Handlera Extends Handler {
Public void handlerequest () {
IF (can Handle) {
DOSMETHING;
} else {
Successor.handlerequest ();
}
}
}
Public Class Handlerb Extends Handler {
Public void handlerequest () {
IF (can Handle) {
Doanotherth;
} else {
Successor.handlerequest ();
}
}
}
e) Summary:
I. To maintain the back relay chain.
II. For request, you can use hardcoded representation, or encapsulate requests.
III. Help system is an app for Chain of Responsibility.
2. Command mode
a) Structure:
Note: 1) Package a request to an object, so that you can use different requests to parameterize the customer, queuing or logging the request log, and supports the revocable operation.
b) Advantages:
i. Pack the requesting process into a specific class instead of determining and assigning a string IF-ELSE statement. (The event model in JDK1.2 is implemented through the IF-ELSE, starting from J2SDK, the event model is in the form of Command mode)
Ii. Request sequence can be recorded to implement UNDO operations. (Because it is triggered in the Invoker, you can record the events that have happened at Invoker. Or by providing a global event log, every time Command performs its execute () method, first in this log Fill in, implement the recording of the request queue)
c) Use the environment:
i. Specify, arrange, and execute requests at different times. A CommMand object can have a survival that is independent of the initial request. If a requested recipient can be expressed in a manner that is independent of address space, the command object responsible for the request can be transmitted to another process and implement the request there. Ii. Support cancel operation. (Inside the Command, the status record is performed in the beginning of the execute method)
III. Support for modification logs so that these modifications can be re-made once when the system crashes. (Because the request queue is recorded, it can be done)
IV. Constructs a system with high-level operations that constructs primitive operation, such a structure is common in the information system that supports transactions. A transaction encapsulates a set of changes in the data, and the CommMand mode provides a method of modeling transactions. CommMand has a public interface that allows you to call all transactions in a way. At the same time, it is also easy to add new transactions to expand the system.
d) Code instance:
Public class invoker {
Private command [] Commands;
Public void onevent (event e) {
IF (e) {
Commands [i] .execute ();
}
}
}
Public interface command {
Public void execute ();
}
Public class receiver {
Public void action () {}
}
Public class commanda implements command {
PRIVATE Receiver Rec;
Public void execute () {
Rec.action ();
}
}
e) Summary:
i. Command mode can result in a lot of small classes. (Can be solved by internal class)
II. Java event model is an application of the Command mode, where ActionListener is equivalent to the Receiver in the above.
3. Iterator mode
a) Structure:
Note: 1) Provide a method sequence to access the individual elements in a polymerization object, and do not need to expose the internal representation of the object.
b) Advantages:
i. In the case where there is no need to expose the set of exposed sets, a method of traversing a collection is provided. (Because it is responsible for creating Iterator, only Iterator knows the internal structure of the collection, and this collection structure is transparent to the user)
c) Use the environment:
i. Access the contents of a collection object without exposing her internal representation.
II. Supports various traversal of the aggregation object.
Iii. Provides a unified interface to traverse different aggregates. (All operations are defined in Iterator)
d) Code instance:
Public interface aggregate {
Public iterator creteiterator ();
Public int size ();
Public node getNode (int index);
}
Public interface itrator {
Public void first ();
Public void next ();
Public boolean isdone (); public node current ();
}
Public class aggregatea imports aggregate {
Public iterator createTeiterator () {
Return New Iteratra (this);
}
}
Public class itratora imports iterator {
PRIVATE AGGREGATE AGG;
Private int current;
PRIVATE INT SIZE;
Public void first () {
CURRENT = 0;
}
Public void last () {
Current = Size - 1;
}
Public void isdone () {
IF (current == size)
Return True;
Else
Return False;
}
Public node current () {
Return Agg.GetNode (CURRENT);
}
}
e) Summary:
i. Who controls the traversal. There are generally two methods. First, the customer program is responsible, the other is responsible by the traversatizer. The previous way is flexible, but the class reuse is small, and the coupling is large. The latter flexibility is not as good as the former, but he can be easily reused, optimized, and reduces the coupling between the client program and the collection.
Ii. Who defines override algorithms. There are generally two options. First, it is defined by the collection itself, and then saves the status to the traverster, the other is the responsibility of the traveler. The former method facilitates the saving of the collection of private information, and does not expose the traversatizer. The latter method, more flexible, and the same traversal algorithm can be reused on different collections.
Iii. Processing synchronization operation. When a traveler is traversed, if the collection is deleted, it may cause a repetition to access, or if a collection of elements, it is necessary to provide a means to ensure that the above is not taken.
IV. Empty Track. Recursive to the Composite object. The traversal access to the tree collection can be completed by providing an emotion in the leaf node (ISDONE method always returns TRUE).
v. Itrator in the Util package in Java is an application for this mode.
4. Mediator mode
a) Structure:
Note: 1) Encapsulate a series of object interactions with an object. Mediator makes the objects need not be explicitly cited to each other, making it coupling, and can independently change their interaction between them.
b) Advantages:
i. Reduce the coupling between the objects, locate the behavior of the object in the inside of the object. (All colleague communications are concentrated in Mediator)
II. By modifying the code of Mediator, you can easily change the interaction between the objects.
Iii. It is easy to add new colleague in the system without changing existing code. (Colleague only communicates with Mediator, they don't know each other)
IV. Mediator solves the problem of understanding the details of other objects when the Command object needs to understand other objects when executing the code.
c) Use the environment:
i. A set of objects communicate well, but complex,, generating interdependent relationships and difficult to maintain. (Mediator is used to decoup) the communication between the objects) II. An object references many other objects and communicates directly with these objects, causing difficult to multiplexing the object.
III. To customize a behavior distributed in multiple classes, do not want to generate too much subclasses.
d) Code instance:
Public interface mediator {}
Public class mediatora imports mediator {
PRIVATE Colleague A;
Private colleague b;
Public Mediator () {
a = new colleaguea (this);
B = New colleagueb (this);
}
Public void dosomething (colleague c) {
b.doanotherthing ();
}
}
Public Abstract Class Colleague {
Protected Mediator M;
Public Colleague (Mediator M) {
THIS.M = m;
}
}
Public class colleaguea eXtends colleague {
Public colleaguea (Mediator M) {
Super (m);
}
Public void dosomething () {
M.DOSMETHING (THIS);
}
}
Public class colleagueb extends colleague {
Public colleagueb (mediator m) {
Super (m);
}
Public void doanotherthing () {
...
}
}
e) Summary:
i. Mediator mode can reduce subclass generation. She concentrated together in each colleague to communicate together, changing these behaviors only need to generate Mediator's subclasses, such that the Colleague class can be reused.
She decoupled each colleague sub-class.
She simplifies the object protocol. Change from the original possible N-N to 1-n.
IV. She abstracts the collaboration between the objects.
She makes control concentrates.
Vi. Facade mode is also abstracting the system, providing a convenient interface, but the communication of the FACADE mode is unidirectional, while Mediator is two-way.
VII. Automatic model can consider using Mediator mode to implement.
5. Observer mode
a) Structure:
Note: 1) Define a pair of dependencies between objects, when the status of an object changes, all objects that depend on his object are notified and automatically updated.
b) Advantages:
i. Define an abstract object between communication framework.
c) Use the environment:
i. There are two aspects of an abstract model, one of which relies on the other aspect, and packages both in separate objects to make them independently change and reuse. (This is similar to the Builder mode and Bridge mode.builder mode for object generation, Bridge mode is used for abstract general interface, OBSERVER mode is used to notify the status change)
II. When you change an object, you need to change other objects at the same time, and don't know how much objects have to be changed. (Here is similar to Chain of Responsibility)
III. When an object must notify other objects, and she can't assume who other objects, in other words, you don't want these objects to be closely coupled. (The only relationship between the two is the OBServer must implement an update () method)
d) Code instance:
Public class subject {
PRIVATE Vector OBSERVERS;
Public void addobserver (Observer Observer) {
Observers.Add (Observer);
}
Public Void RemoveobServer (Observer Observer) {
Observers.Remove (OBServer);
}
Public void notify () {
For (Observer o: observers) {
O.Update (this);
}
}
}
Public class subjecta extends subject {
PRIVATE INT State;
Public void statechanged () {
Super.Notify ();
}
}
Public interface Observer {
Public void update (SUBJECT SUB);
}
Public Class Observera IMPLEMENTS OBSERVER {
Public void update (Subject Sub) {
DOSMETHING;
}
}
e) Summary:
i. Abstract coupling between targets and observes. The goal only needs to know that all observes have implemented the update () method.
II. Support broadcast communication. The relationship between the target and the observer is 1-N.
III. Because Observerable is a class, while Java does not support multi-inheritance, if a class has inherited a class, you can use an internal class when you have an OBServerable, let the internal class Inherit the OBSerVerable class.
6. State mode
a) Structure:
Note: 1) Allow an object to change her behavior when it has changed its internal state, and the object seems to have modified her class.
2) Context replaces her State to achieve the purpose of modifying its behavior.
b) Advantages:
i. Locate status information to a separate class. (All State Class)
She transforms the state of the state. (If only the internal data value is only defined when the current state is defined, the status change is only indicated as some variable assignment. However, the independent object is introduced for different states, which can make the transformation more clear)
Iii. Status objects can be shared. (If the State object does not have an instance variable, the State object can be shared, and they avoid the internal state, only the lightweight object of behavior)
c) Use the environment:
i. The behavior of an object depends on her status and she must change her behavior based on the state according to the state. (Similar to the automaton model, bind behavior with status)
II. One operation contains a huge conditional statement, and these branches depend on the status of the object. This state is usually represented by one or more enumerations. There is usually a plurality of operations contain this same conditional structure. The State mode puts each conditional branch into a separate class. This allows you to use the status of the object as an object according to the situation itself, which can independently depending on other objects. d) Code instance:
Public class context {
PRIVATE STATE;
Public void request () {
IF (conditiona) {
State = new statea ();
} else if (conditionb) {
State = new stateb ();
}
State.handle ();
}
}
Public interface state {
Public void handle ();
}
Public class statea imports state {
Public void handle () {...}
}
Public class stateb imports stat {
Public void handle () {...}
}
e) Summary:
i. Who defines the status conversion: If the conversion rule is fixed, it can be defined by context. Another approach is to record her follow-up state by each state, and when the conversion occurs, the state is set by State.
7. Strategy mode
a) Structure:
Note: 1) Define a series of algorithms, encaps them one by one, and enable them to replace each other, this mode makes the algorithm can be varied independently of their customers.
2) The Strategy mode is very similar to the Strategy mode, but the Target of the Strategy mode is to implement the algorithm, there is no order relationship between the algorithm. The target of the State mode is to implement the state transition, and there is a certain order between states.
b) Advantages:
i. Users can dynamically select policies. (Replace Strategy instance)
II. You can add a new algorithm without modifying the customer code. (All STRATEGY subclasses have the same interface)
c) Use the environment:
i. Many related classes are just behavior, "Policy" provides a class of behavior with one of multiple behaviors.
Ii. It is necessary to use different variations of an algorithm.
III. Algorithm uses the data that customers should not know. The policy mode can be used to avoid exposure to complex, with the data structure related to the algorithm.
IV. A class defines a variety of behaviors, and these behaviors appear in the form of multiple conditional statements in this type of operation. The relevant conditions are moved into their respective Strategy classes to replace these statements.
d) Code instance:
Public class context {
PRIVATETEGY Strategy;
Public void selectstrategy (String name) {
IF (Name == Conditiona)
Strategy = new statatea ();
Else
Strategy = new strategyb ();
}
Public void request () {
Strategy.handle ();
}
}
Public interface statate {
Public void handle ();
}
Public Class Strategya IMPLEments Strategy {
Public void handle () {...}
}
Public class statnegyb imports strategy {
Public void handle () {...}
}
e) Summary:
i. The Strategy class level defines a series of available algorithms or behaviors for Context.
II. Pummerate the algorithm used in Context from context, making Context easier to understand and reuse.
Iii. Eliminating complex IF-ELSE statements.
IV. Strategy can provide different implementations of the same behavior. Customers can choose from different strategies based on time / space weighted.
v. If the Strategy mode does not have an internal state, the instance can be shared between each context.
Vi. Sort algorithm, generally implemented as a Strategy for easy sharing and reuse.
8. Template mode
a) Structure:
Note: 1) Define algorithm steps in an operation to delay some steps to the subclass. The Template mode allows the subclass to redefine certain specific steps of the algorithm without changing the structure of an algorithm.
b) Advantages:
i. For public methods can be implemented in base classes, while others can be implemented in subclasses.
c) Use the environment:
i. Distribution of an algorithm in one time, and leave the variable portion to subclasses. (Subclass overload or rewrite the method of parental class)
II. Public behavior in each subclass should be extracted and concentrated into a public parent class to avoid code repetition.
III. Control subclass extensions, the Template method only calls the Hook operation at a specific point, so it only allows expansion at these points. (Method in TemplateMethod, is the extension point)
d) Code instance:
Public Abstract Class AbstractClass {
Public void templateMethod () {
Actiona ();
Actionb ();
}
Public Abstract void Actiona ();
Public Abstract void Actionb ();
}
Public class concreteclass extends abstractclass {
Public void Actiona () {...}
Public void actionb () {...}
}
e) Summary:
i. Template mode defines a directional control structure that is consistent with the requirements of Framework.
9. Visitor mode
a) Structure:
Note: 1) Represents an operation of an element acting in a target structure. She allows you to define new operations that act on these elements without changing the class of each element. (As long as the new Visitor object is defined, the Visit traversed every Element, you can define a new action)
b) Advantages:
i. Execute the same operation between different objects. (Different ELEMENT have the same Accept interface)
Ii. It is convenient to add new operations.
III. Accessible operations are independently related to operations. Related operations are set to Visitor, while others are responsible for maintaining lists or tree relationships, or placed in ELEMENT. c) Use the environment:
i. The structure of an object contains many types of objects. They have different interfaces, and you want to implement these objects, depend on the specific class's operation. (In the Visit operation, you need to transfer Element to Visitor so that Visitor can get what she needs, about Element information)
II. Need many different and unrelated operations for objects in an object structure. And you want to avoid these objects that "pollute" these objects.
VIS
Itor allows you to focus on the relevant operations in a class, when the object structure is shared by many applications, allowing each app that allows each app that only needs to be used. (Specific operations are defined in the Visit method)
III. Define the class of the object structure rarely change, but often needs to define new operations on this structure.
d) Code instance:
Public interface visitor {
Public void Visita (Element E);
Public void Visitb (Element E);
}
Public class visitora imports visit visitor {
Public void Visita (ELEMENT E) {...}
Public void Visitb (ELEMENT E) {...}
}
Public class visitorb imports visits visitor {
Public void Visita (ELEMENT E) {...}
Public void Visitb (ELEMENT E) {...}
}
Public interface element {
Public Void Accept (Visitor V);
}
Public class elementa imports element {
Public void accept (Visitor V) {
v.visita (this);
}
}
Public class elementb imports element {
Public void accept (Visitor V) {
v.visitb (this);
}
}
e) Summary:
i. Adding new Element subclasses is difficult. Because this needs to modify the structure of the entire Visitor and add a new Visit method.
Ii. Destroying package. Because Visitor wants to successfully execute his Visit method, you need to understand the internal information of Element, which causes Element to provide some ways to expose its internal details.
10. Behavioral mode discussion
a) Package changes:
i. A StraterGy object package an algorithm.
Ii. A State object packages a state-related behavior.
Iii. A protocol between the Mediator object package object.
IV. A method of accessing and traversing each component in an aggregated object.
v. A MEMENTO object encapsulates the internal state of the object.