Good book finishing series - design mode: can be used for object-oriented software foundation 5.5

zhaozj2021-02-08  256

5.6 MEMENTO - Object Behavior Model 1. It is intended to capture an internal state of an object without damaging the encapsulation, and save this status outside of the object. This will restore the object to the originally saved state. 2. Alias ​​to k e n3. Motivation sometimes necessary to record an internal state of an object. In order to allow users to cancel uncertain operations or recover from errors, they need to implement checkpoints and cancels, and to implement these mechanisms, you must save status information in advance to restore objects to their previous status . However, objects typically encapsulate parts or all of the status information such that their status cannot be accessed by other objects, and it is not possible to save its status outside of the object. The principle of exposure to its internal state will violate the package, which may damage the reliability and scalability of the application. For example, consider a graphic editor that supports connection between graphics objects. The user can connect two rectangles with a straight line, while the two rectangles can remain connected when the user moves any of the rectangles. During the movement, the editor automatically stretches this straight line to keep the connection. A method of well-known way to maintain an inter-object connection relationship is to use a constraint interpretation system. We can package this feature in a C O N S T R object. C O N S T R A I N T S O L V ER Records these connections and generates a mathematical equation that describes their mathematical equations when the connection is generated. When the user generates a connection or modification graph, C O N S T R A I N T S O L V is solved these equations. And re-adjust the graph according to its calculation results, so that each object remains the correct connection. In this application, it is easy to support cancel operation. An obvious method is that the movement of the moving distance is saved each time, and the object moves back to the equal distance when the movement is canceled. However, this cannot guarantee that all objects will appear in their original place. Imagine some relaxation in a connection during the movement. In this case, the rectangle is simply moving back to its original location and does not necessarily get the expected results. In general, the public interface of ConstraintSolver may be insufficient to accurately reverse its role in other objects. To rebuild the previous state, the cancel operation mechanism must be more closely coupled with C O N S T R A I N T S O L V, but we should also avoid exposing the internal exposure of C O N S T R A I N T S O L V E R to the cancel operation mechanism. We can solve this problem with the Memo (M E M E N TO) mode. A memo (M E M E N T O) is an object that stores another object in an instantone, while the latter is called the primary organ of the memo (O R I g i n a t O r). When you need to set the primary checkpoint, the cancel operation mechanism requests a memo to the primary. The primer initializes the memo with the information describing the current state. Only the primer can access information to the memo, and the memo "is not visible" for other objects. In the example of the graphic editor just discussed, CONSTRAINTSOLVER can act as a primary. The following event sequence describes the process of canceling operation: 1) As a side effect of the mobile operation, the editor requests a memo to C O N S T R A I N T S O L V ER. 2) C O N S T R A I N T S O L V Er creates and returns a memo, in which the memo is an example of the S O L V E R S T A TEE class. The S O L V E R S T A T E Memore contains some data structures that describe the internal equation of C O N S R A I N T SO L V E R and the current state of the variable. 3) After the user cancels the movement operation, the editor sends the S O L V E R S T A TEM to the C O N S T R A I N T Ss O L V E R. 4) According to the information in the S O L V E R S T A T E Memor, constraintsolver changes its internal structure to accurately return its equation and variables to their respective states.

This solution allows C O N S T R A I N T S O L V ER to give the information required to restore the previous state to other objects, and does not expose its internal structure and representation. 4. Applicability Use Memo mode in the following situations: • You must save an object (partially) state at a certain time so that it will be restored to the previous state. • If an interface allows other objects directly to these states, the implementation details of the object will be exposed and the encapsulation of the object is destroyed. 5. Structure Chapter 5 Behavior Mode 1 8 96. Participants • ME E M E N T O (Memo, such as S O L V E R S T A T E) - The memo stores the internal state of the original hairman object. The primer determines which internal status of the memo stores as needed. - Prevent other objects other than the primary vessel from accessing memo. The memo actually has two interfaces, the manager (C A R e t a k e r) can only see the narrow interface of the memo - it can only pass the memo to other objects. Instead, the primer can see a wide interface that allows it to access all the data returned to the previous state. Ideally, only the original state of this memo is allowed to generate this memorandum. • O R I g i n a t O r (Primer, such as C O N S T R A I N T SO L V) - The original initiator creates a memo to record the current time it's internal state. - Use memo to restore internal status .. • C A r e t a k e r (responsible, such as undo means) - responsible for keeping a memorandum. - Do not operate or check the contents of the memo. 7. Collaboration • Manager requests a memo to the primary, retains it back to the primary, as shown in the interaction diagram below. Sometimes managers do not return a memo to the primary, as the primer may not need to refund the previous state at all. • The memo is passive. Only the primer that creates a memo will assign and retrieve it. 8. Effects Memo mode There are some effects: 1) Keep the encapsulation boundary to use the memorandum to avoid information that should only be managed outside the primary by the primer management but must be stored. This mode protects the internal information of O R I g i n a t O r possible to other objects to maintain the package boundary. 2) It simplifies the primary device in other maintained encapsulation design, originator is responsible for maintaining the internal state version of the customer request. This is handed over to O R I g I n a t O r. Let customers manage their requests will simplify O R I g I n a t o r, and make the primary universal when the customer works. 3) Using the memo possible price Very high If the primer must copy and store a lot of information when generating a memo, or the customer creates a memo and restoring the original initiator status very frequently, it may result in very large overhead. This mode may not be appropriate unless the cost of the encapsulation and recovery O R I g i n a t O R is not large. See Implementation 1 9 0 Design Mode for Incremental Changes: Documentation Foundation

discuss. 4) Define narrow interfaces and wide interfaces may be difficult to ensure that only primers can access the memorandum. 5) Maintenance Memorandial Executive Manager is responsible for deleting the memo it maintains. However, the manager does not know how many status in the memo. Therefore, when the storage is stored, a very small manager may generate a lot of storage overhead. 9. Implementing the following is two issues that should be considered when implementing a memo mode: 1) Language support memo has two interfaces: a wide interface used by the primer, a narrow interface used for other objects. The ideal implementation language should support two static protection. In C , O R I g I n can be used as a friend of M e m e N T O, and the M e m e n t o wide interface is private. Only narrow interfaces should be declared as public. For example: 2) Storage incremental change If the order in which the memo creation and its return (given to the primary distributor) are predictable, the memo can only store incremental changes in the internal state of the primary. For example, a historical list containing the revoked commands can use a memo to ensure that they can be restored to the correct state when the command is canceled (see C O m M A N D (5. 2)). The historical list defines a specific order, and the command can be canceled and re-made. This means that the memorandum can only store the incremental change in an order rather than the integrity of each object it affects. In the example given in front of the front Motivation, the constraint monitors can only store those changed internal structures to keep the straight lines to rectangular, rather than storing the absolute positions of these objects. 10. Code Example The C code given here here is shown in the previously discussed CO N S T R A I N T S O L V ER. We use the M O V E C O m M A n D command object (see C O m M A N D (5. 2)) to perform (cancel) a graphical object from a position to another location. The graphic editor calls the E x E C U t e operation of the command object to move a graphics object, and use U n e x e c u t e to cancel the movement. The command object stores its goal, the move distance and an example of a C O N S T R A I N T S O L V, which are a memo containing a constraint interpreter. The connection constraint is created by C O N S T R A I N T S O L V E R Class. Its key member function is SOLVE that explains the constraints of those registered by A D D C O N S T R A I N T. To support the cancel operation, ConstraintSolver uses C R E A T E M E M E N T O operation to store its own state in an example of a C O N S T R A I N T S O L V e r m e m e n t O example. Calling S e tm e m e n t o allows the constraint interpreter to return to a previous state. C O N S T R A I N T S O L V E R is a S I N G L E T O N (3. 5). For these interfaces, we can implement the member function E x e c u t e and u n e x e c u t e and u N e x e c u t e below: 1 9 2 Design mode: the basis for object-oriented software

E x e c u T e acquires a Memory of C O N S R A I N T S O L V E R M E M E N TO before moving graphics. U N e x E C U TE first moves the graphic back, and then set the state of the constraint interpreter back to the original state and finally let the constraint interpreter explain these constraints. 11. The code example of known applications is supported from the Connections implemented by C S O L V ER [V L 9 0] in U N i D R A W. The C O L E C T I O N [A P 9 2] in D Y L A n provides an iterative interface that reflects the memo mode. D Y L A N has a collection of "status" objects, which is a memo represents an iterative state. Each collection can represent the current state of iteration according to any of its choices; the representation is completely invisible to the customer. The iterative method of D Y L A n is converted to C can be represented as follows: C R E A TEE N I T I a L S T A TEE is returned to the set returns an initialized I T E R A T I O N S T A T E object. N e x t advances the status object to the next position of the iteration; in fact it will be ussed. If n e x t has exceeded the last element in the collection, I S D O N e returns T R u e. C u R R e n t i t e m Returns the element of the status object that is currently referred to. The C O P y returns a copy of the given state object. This can be used to mark some point in the iterative process. Given a class I t e M Type, we can be iterated on the collection below in its instance: Chapter 5 Behavior 1 9 3

Note We delete the status object at the end of iteration. However, if P R O C e s I t e m throws an exception, the delete will not be called so that rubbish is generated. This is a problem in C , but there is no problem in D Y L A n, because D Y L A n has garbage collection mechanisms. We discussed a solution to this problem in Chapter 5. There are two interesting advantages based on the iterative interface based on the memo: 1) There are multiple states in the same collection. (I TE E R A T O R (5. 4) mode is also true.) 2) It does not need to destroy a collection of encapsulation for support iteration. The memo is only explained by the collection itself; any other object cannot access it. Other ways to support iteratively require an iterator class as a friend of their collection class (see Iterator (5.4)), thereby destroying encapsulation. This is no longer present in the implementation based on the memo. At this time, C O L E C T I O N is a friend of I T E R A T O R St A T E. Q O c A constraint interpretation tool stores increment information in a memo [H h M v 9 2]. Customers can get a memo that is currently explained in a constraint system. The memorandum only includes those constraint variables that have changed from the previous interpretation. Usually each new interpretation is only a small part of the interpreter variable change. This changed variable subset is enough to restore the interpreter to a previous explanation; the interpretation of the recovery requires gradually recovery through the intermediate explanation. So you cannot set a memo in any order; QoCA relies on a historical mechanism to return to the previous explanation. 12. Related Mode Command (5.2): The command can use the memo to operate the revocable operation. Iterator (5.4): Memorial as described above can be used for iteration .5.7 Observer (observer) - Object behavior mode 1. Integrate a one-to-many dependency between the objects, when an object is changed, All objects that depend on its object are notified and automatically updated. 2. Decname Dependents, Release - Subscribe (P UB L I S H - S UB S C R I B E) 3. The motivation segmented a system into a series of collaborative classes with a common side effect: need to maintain the consistency between related objects. We do not want to make all kinds of close coupling in order to maintain consistency, as this reduces their reusability. For example, many graphical user interface toolbox indicate the interface of the user application to the application data below the application data [K P 8 8, LVC89, P 88, WGM88]. Define the class of application data and the classes responsible for the interface representation can be independently multiplexed. Of course they can work together. A table object and a histogram object can describe the information of the same application data object using different representations. Table objects and histogram objects do not know each other, so that you can multiplex table or histograms as needed. But here is what they behave seem to know each other. When the user changes the information in the table, the histogram immediately reflects this change, and this is true. 1 9 4 Design mode: can be used for object-oriented software

Observers target changes notification query, updating this behavior means that the table objects and rod-like objects are dependent on the data object, so any status of the data object should be notified immediately. There is also no reason to define the number of objects of the data object to two, and the same data can have any number of different user interfaces. O b S E R V be describes how to establish this relationship. The key object in this mode is the target (S UB J E C T) and the Observer (O B S E R V E R). A goal can have any number of observer dependent on it. Once the status of the target changes, all observes are notified. As a response to this notification, each observer will query the target to synchronize its status with the status of the target. This interaction is also called publishing - subscription (P U B L I S H - S UB S C R I B E). The goal is the publisher of the notification. It does not need to know who is its observer when notification. You can have any number of observed subscriptions and receive notifications. 4. Applicability can use the observer mode in any of the following conditions: • One aspects are dependent on the other aspect. The two are encapsulated in separate objects to make them independently change and reuse. • When changing a change in an object needs to change other objects at the same time, do not know how many objects have to be changed. • When an object must be notified other objects, it can't assume who other objects are. In other words, you don't want these objects to be closely coupled. 5. Structure 6. Participants • S U b J E C T (Target) - The target knows its observer. There can be any other observer to observe the same goal. - Provide the interface to register and delete the observer object. • O b S e R V E R (Observer) - Defines an update interface for those subjects that require notification when changing at the target. • C O N C R E TET E S UB J E C T (Specific Objectives) - Store the relevant state into each C O N C R object object. - A notification is issued when there is a change in its state changes. • C O N C R e t e O b S e R V E R (Specific Observer) - Maintains a reference to the C O N C R e t e S UB J E C T object. - Storage is related to the state, which should be consistent with the status of the target. - Realize the update interface of O b S E R V E R to keep the state of the self with the status of the target. Chapter 5 Behavior Model 1 9 5

7. Collaboration • When C O N C R e t e S U b J E C T can cause a change in its observer with its own state inconsistent, it will inform it. • After obtaining a specific target change notification, the ConcreteObserver object can query information to the target object. C O N C R E TET EO B S E R V E R Use this information to make it consistent with the status of the target object. The following interaction illustrates a collaboration between a target object and two observes: Note that the O b S E R v ER object that makes a request is not updated immediately, but it is postponed to it from the target to get a notification. N o T i f Y is not always called by the target object. It can also be called by an observer or other object. Implementation will discuss some common changes. 8. Effects O b S E R V mode allows you to independent changes targets and observes. You can reuse the target object alone without having to reuse the observer at the same time, and vice versa. It also enables you to increase the observer without changing the target and other observer. Here is some other advantages and disadvantages: 1) Abstract Coupling between targets and observes, only one series of observers, each in line with an abstract O b S e R V. simple interface. The goal does not know which specific class belongs to any observer. The coupling between the target and the observer is abstract and minimal. Because the target and observer are not closely coupled, they can belong to different abstractions in a system. A lower level target object can communicate with a higher level and inform it, so that the system hierarchical is complete. If the target and the observer is mixed in one, the obtained object is either transversely two levels (violating the hierarchical), or must be placed in a certain layer of the two layers (this may impair the level of abstraction). 2) Support broadcast communication is unlike usual request, the notification of the target transmission does not need to specify its recipient. The notification is automatically broadcast to all related objects that have been registered to the target object. Target objects don't care how many objects are interested in yourself; its only responsibility is to inform the observer of it. This gives you the freedom to increase and delete the observer at any time. Is the handling or ignore a notification depends on the observer. 3) Accidental updates Because an observer does not know the existence of other observes, it may not know anything about the final price of the target. A similarly harmless operation in the target may cause a series of updates to observers and those objects that depend on these observers. In addition, if the definition or maintenance of the criteria, it is often caused by errors, which is often difficult to capture. Simple update protocols do not provide specific details Description Overwhelming, which makes the above problems more serious. If no other agreement helps the observer finds what has changed, they may be forced to minimize changes. 1 9 6 Design mode: can be used for object-oriented software

9. Realize this section to discuss some issues related to the implementation of dependencies. 1) Creating a target to map a target object between its observes tracking the easiest way to track the observer that it should notify is explicitly saving them in their target. However, when the target is small and the observer is small, such storage may be too high. A solution is to use a time-to-room, with an associated lookup mechanism (eg, an H A S h table) to maintain the target to the observer mapping. Such a target without the observer does not produce a storage overhead. But on the other hand, this method increases the overhead of accessing the observer. 2) Observe that multiple goals in some cases, one observer may make sense to depend on multiple objectives. For example, a table object may depend on multiple data sources. In this case, the U P D A TE-interface must be extended to make the observer know which target sent. Target objects can simply use one of the parameters that operate in U P D A TE E, so that the observer knows which target should be checked. 3) Who triggered an update goal and its observer relies on the notification mechanism to be consistent. But which object calls N o T I f y to trigger updates? There are two options at this time: a) When the status setting operation of the target object is automatically called automatically after changing the status of the target object, N O T I f Y. The advantage of this method is that the customer does not need to remember to call N O T I f y on the target object, the disadvantage is that multiple consecutive operations generate multiple consecutive updates, which may be less efficient. b) Let customers call N O T I f y when appropriate. The advantage of doing this is that the customer can trigger updates one-time after a series of state changes, avoid unnecessary intermediate updates. The disadvantage is to add responsibility for trigger updates to customers. Because customers may forget to call N o T i f y, this way is more vibration. 4) Be careful not to pay attention to the suspension reference to the target in its observer on the deleted target suspension reference. A method of avoiding a suspension is that when a target is deleted, it will notify it to reset the reference to the target. In general, the observer cannot be simply deleted, as other objects may reference them, or may also observe other goals. 5) Make sure that the status of the target itself is consistent with the notification, it is important to ensure that the status itself is important before the notification is issued, because the observer needs to query the current state of the target during the update of its state. When the subclass of S U b J E C T is called inherited, it is easy to inadvertently violate this itself. For example, in the following code sequence, when the target is still in an inconsistent state, the notification is triggered: You can send a notification in the template method in the abstract S ubject class (Template Method (5.10)) to avoid this error. Define those primitive operations that those subclasses that can be redefined, and the N O T I f Y as the last operation in the template method, so that when the subclatrifier defines the operation of S UB J E C T, it is also possible to ensure that the state of the object is consistent. By the way, it is always possible to record which S U b J E C t operation trigger notification is always in the document. Chapter 5 Behavior Model 1 9 7

6) Avoiding an observer-specific update protocol - implementation of the push / pull-mode observer mode often needs to broadcast other information about its changes. Targets These information is used as U P D A TE to manipulate a parameter. The amount of this information may be small, or it may be large. One extreme is that the target sends details of the change to the observer regardless of whether they need or not. We call it a push model. The other extreme is a pull model; the target does not send anything out of the minimum notice, and after this, it is revealed to the target inquiry. The pull-mode emphasizes that the target does not know its observer, and the model assumes that the target knows the needs of some observer. The push model may make the observer difficult to multiplex because the target's assumption may not always be correct. on the other hand. The pull-up type may be poorly efficient because the observer object needs to change anything without the target object help. 7) Explicitly specify the change in interest You can extend the target's registration interface, so that the observer is registered as only interested in specific events to improve the efficiency of the update. When an event occurs, the target only notifies the observer that has been registered as interested in the event. Supporting this approach is a way to use the concept of using the target object (A S P e c T s). Use the following code to register the observer object as a specific event for the target object: Void Subject :: attach (observer *, aspect & intert); here I N T E R E S T specifies the event of interest. At the time of the notification, the target will change this as an observer that the U PDate operation is provided to it, for example: void observer :: Update (Subject *, aspect); 8) Package complex update semantic target and When the dependency between the observer is particularly complex, there may be a subject to maintain these relationships. We call such an object to change the manager (C H a ​​N g E m a n a g e r). Its purpose is to minimize the workload required to reduce the status change of the observer reflect the status of its goals. For example, if an operation involves changes to several mutual dependent targets, it must be guaranteed that only the observer is notified once, rather than each goal notifies the observer. . CH A N g e m a n a g e r has three responsibilities: a) It maps a goal to its observer and provides an interface to maintain this mapping. This does not need to be referenced by the goal to the reference to its observer, and vice versa. b) it defines a specific update policy. c) According to a request request, it updates all observes depend on this goal. The block diagram of the next page describes the implementation of the O b S e R V e R mode based on C H a ​​N g E M a N A g e R. There are two special CH a N g E m a n a g e r. S i m p L E C H A N g E M A n g e r is always updated all of the observes of each target, relatively simple. In contrast, D A g c H a N g e m a n a g e r handling target and a ringless directional view of the dependency between the observer. When an observer observes multiple targets, DagchangeManager is better than S i m p L E C H A N g E M A N g er. In this case, changes in two or more targets may generate redundant updates. D A g c h a n g e m a n a g er ensures that the observer only receives an update. Of course, SimpleChangeManager is better when there is no multiple update issues. C H a ​​N g e m a n a g e r is an example of a M e D i a T O R (5. 5) mode. Usually only one C H a ​​N g e m a n a g e r is globally visible. Here S i n g l e t o n (3. 5) mode may be useful. 9) Binding of the class libraries written by the target class and the observer that does not support multiple inheritance (such as S M a L t a lk) class libraries typically not separate S UB J E C T and O B S E R V E R classes, but combine their interface into a class.

This allows you to define an object that is both a target and an observer without a multiple inheritance. For example, in S M A L t a lk, Subject and O B S e R V ER interface 1 98 Design mode: The foundation of the object-oriented software is defined in root OB J E C T, so they can be used for all classes. 10. Code Example An abstract class defines the O b S E R V ER interface: This implementation supports a number of targets for an observer. When the observer observes multiple targets, the target as a parameter is transmitted to the UP D A TEE operation allows the observer to determine which target changes. Similarly, an abstract class defines S U b J E C T interface: Chapter 5 Behavior 1 9 9

C L O c k Ti M E R is a specific objective for storing and maintaining a day. It informs it once every second. C l O c k Ti M E R provides an interface for removing a single time unit such as hours, minutes, and seconds. The Ti Ck operation is adjusted by an internal timer at a fixed time interval to provide a precise time baseline. Ti C K updates the internal state of C L O c k Ti M e R and calls N o T I f y to notify the viewer: Now we can define a D i g i t a l c l O C K class to display time. It inherits its graphics feature from the Wi D g e T offered from a user interface toolbox. By inheriting O b S e R v E R, the OBServer interface is integrated into the interface of D i g i t a l c l o c k. Before U P D A TE operation draws the clock pattern, it checks to ensure that the goal of issuing notifications is the target of the clock: 2 0 0 Design mode: can be used for object-oriented software

One A N A L O g C L O c k can be defined by the same method. The following code creates a A n a l o g c l o c k and a DigitalClock, which always displays the same time: Once t i m e r moves, the two clocks will be updated and redisplayed correctly. 11. The earliest application of known applications is also the most famous O BServer mode examples appear in the MLLTalk M Odel / Vi EW / C Ontrol -ler (MVC) structure, which is in the S MallTalk environment [KP 8 8] User interface frame. M v C's M o D e l serves as a target of the target, while Vi e w is the base class of the observer. SmallTalk, ET [WGM88], and TH I N K ClassLank [S Y M 9 3 B] all in the S UB J E C T and O B S E R V ER Interfaces in the parent class in all other classes in the system, thereby providing a universal dependency mechanism. Other user interface tools using this mode include I N T E R VI E W S [LVC89], Andrew To O L K i T [P 8 8] and U N i D R A W [V L 9 0]. I N t e R VI e w s Explicitly defines O b S E R V ER and O B S E R V A B L E (Target) class. A n d r e w referred to as "view" and "data objects", respectively. U N i D R A W divides the graphic editor object into VI E W (observers) and S UB J E C T. 12. Related Mode Mediator (5.5): By encapsulated complex update semantics, ChangeManager acts as the intermediaries between the target and the observer. S i n g l e t o n (3. 5): ChangeManager can use S i n g l e t o n mode to ensure that it is unique and is available globally. 5.8 State - Object Behavior Type 1. The intention allows an object to change its behavior when its internal state changes. Objects seem to modify its class. 2. Otalog State Object (Objects for State) 3. Motivation considers a T C P C O N n e C T I O N representing the network connection. The state of a T C P C O N n e c t i O n object is one of several different states: the connection has been established (E S T A B L I S H E D), is listening (L i S t e n g), the connection is closed (C L O S e d). When a T C P C O N e c t I O N receives a request for other objects, it makes different reactions based on their current state. For example, Chapter 5 Behavior mode 2 0 1

The result of an O P e n relies on whether the connection is connected to the closed state or the connection has been established. The S t a t e mode describes how T C P C O N E C T I O N exhibits different behavior in each state. The key idea of ​​this mode is to introduce an abstraction called T C P S t a t e to represent the connection state of the network. T C P S T A T E Class is a public interface that represents different operating states. The subclass of T C P S t a t e achieves behavior associated with a particular state. For example, TCPestablished and T C L O S e D achieve a behavior that the connection to which T C P C O N E C T I O N has established state and connection has been closed. T C P C O N n E C T I O N Maintains a state object indicating T C P to connect the current state (an example of a T C P S t a t e subclass). T C P c O N n E C T I O N classes entrust all requests related to state to this status object. T C P C O N E C T I O N uses its T C P-t a T E sub-class example to perform an operation specific to the connection state. Once the connection status changes, T C P C O N E C T I O N object changes the status object it uses. For example, when the connection is turned from the established state to a closed state, TCPConnection uses an example of the original T C P E S T A B L I S HE D using an example of T C P C L O S E D. 4. Applicability can use the S t a t e mode in both cases: • A object's behavior depends on its status, and it must change its behavior based on the state according to the state. • One operation contains huge multi-branch conditional statements, and these branches depend on the status of the object. This state is usually represented by one or more enumerations. Typically, there is a plurality of operations comprising this same conditional structure. The S t a t E mode puts each conditional branch into a separate class. This allows you to use the status of the object as an object based on the situation itself, which can independently depend on other objects. 5. Structure 6. Participants • C O N t e x t (Environment, such as T C P C O N E C T I O N) - Defines the interface of interest to the client. 2 0 2 Design mode: can be used for object-oriented software

- Maintain an example of a C O N C R e T E S T A T E subclass, this instance defines the current state. • S t a t e (status, such as T C P S t a t e) - Define an interface to encapsulate a particular state of C O N TE E X T. • ConcreteState Subclasses (specific status subclass, such as Tcpestablish, TCPListen, TCPCLOSED) - Each subclass implements a status associated with a state of C O N T E X T. 7. Collaboration • C O N t e x T will delegate the request with the state to the current C O N C R e T E S T A T E object processing. • C O N t e x T can pass itself as a parameter to the status object that processes the request. This allows the status object to access C O N t e x t when necessary. • C O N t e x t is the main interface used by the customer. The customer can use the status object to configure a C O N t e x t, once a C O N t e x T is configured, its customer no longer needs to be dealt with the status object. • C O N t e x T or C R e t e S t a t a subcatencies can determine which state is another successor, and what conditions are performed under the conditions. 8. Effects S TATE mode There are some effects: 1) It will be locally established with specific states, and the behavior of different states is separated to S Tate mode to put all behaviors related to a specific state in one. Object. Because all of the status-related code exists in a S T A T E subclass, new status and conversions can be easily increased by defining new subclasses. Another method is to use the data value to define internal states and let C O N t e x T operations to explicitly check this data. But this will make a conditional statement or C A S E statement that looks similar in the implementation of the entire C O N t e x T looks like. Increasing a new state may need to change several operations, which makes maintenance complex. The S t a t e mode avoids this problem, but another problem may be introduced because the mode is distributed in multiple S T a T E subclass in this mode. This increases the number of subclasses, which is not compact enough relative to a single class. But if there is a lot of status, this distribution is actually better, otherwise you need a huge conditional statement. As a long process, huge conditional statements are unwelcome. They form a big whole piece and make the code are not clear enough, which makes them difficult to modify and expand. The S t a t e mode provides a better way to organize code related to a specific state. The logic that determines the state transfer is not in the single block I f or S W I T, but is distributed between the S t a T E subclass. Pack each state conversion and action into a class, an eye point is enhanced from the execution state to the entire object. This will make the code structure and make it clearer. 2) It makes status conversion Explicitly when an object is only in the internal data value to define the current state, its status is only the assignment of some variables, which is not clear enough. The independent object introduced to different states makes the conversion more clear. Moreover, the State object ensures that c ontext does not cause internal state inconsistency, because from the angle of C ontext, status conversion is atomic - just restroom a variable (ie C ontext S Tate object variable), and No need to assign a value of multiple variables [D CLF 9 3]. 3) The State object can be shared if the S t a t e object does not have an instance variable - that is, the state they represent is completely encoded in their type - then each C O N t e x T object can share a S t a t e object. When the state is shared in this manner, they must have no internal state, only a lightweight object of behavior (see f L Y W E I G H T (4. 6)). 9. Realize how many aspects of S T a TE E-mode: Chapter 5 Behavior 2 0 3

1) Who defines the status to convert the S t a t-mode does not specify which participant defines the status conversion criterion. If the criterion is fixed, they can be fully implemented in C O N t e x t. However, if the S t a t e subclass itself specifies their subsequent state and when converting is performed, it is usually more flexible and more appropriate. This requires C O N t e x t to add an interface to explicitly set the current state of C O N t e x T explicitly. The dispersion logic with this method can easily define the new S T A T E subclass to modify and expand the logic. A disadvantage of this is that a S t a t e subclass has at least one other subclass of information, which has a realization dependence. 2) Another method based on the table In C Programming Style [Car92], CARG IL describes another method on which the structure is loaded on a state-driven code: he uses a table to map the input to status conversion. For each state, a table maps each possible input to a subsequent state. In fact, this method maps the conditional code (and virtual functions in S TI TE E-mode) into a lookup table. The main benefits of the table are their rules: you can change the criteria for status transformation by changing the data rather than changing program code. However, it also has some shortcomings: • Finding tables is often better than (virtual) function call efficiency. • Use a unified, form of form to indicate that the conversion logic makes the conversion criterion become clear and difficult to understand. • It is usually difficult to add some of the actions that accompany state transitions. The method of the table driver describes the state and the conversion between them, but this mechanism must be expanded to perform any calculations on each conversion. The main difference between the table-driven state machine and the S t a T E mode can be summarized as follows: STATE mode models the behavior associated with state, and the table driven method focuses on the defined state conversion. 3) Creating and destroying a common worth considering implemented implementation is that (1) Create them only when you need a S Tate object, and then destroy them, or (2) create them in advance and never never always Destroy them. When the state to be entered is unknown at runtime, and when the context does not change the state frequently, the first choice is preferred. This method avoids creating objects that will not be used, which is important if the S t a t e object stores a large amount of information. When the state changes very frequently, the second method is better. In this case, it is best to avoid destroying status because they may be used again. At this point, you can pay the overhead of the creation of each status object, and there is no overhead of the destruction state object at all during the run. But this method may be less convenient because C O N TE E X T must save references to all states that may enter. 4) Use dynamic inheritance to change a behavior of a response to a specific request to change the method of changing this object in runtime, but it is impossible in most object-oriented programming languages. S e l [u s 8 7] and other delegated languages ​​are exceptions, which provide this mechanism to directly support S T A T E mode. Objects in S E L f can delegate the operation to other objects to achieve some form of dynamic inheritance. The target of the inheritance is effectively changed at runtime. This mechanism allows objects to change their behavior, that is, changing their classes. 10. Code Example The following example gives the C code of the T c P connection example described in the Motivation section. This example is a simplified version of the T C P protocol, which is not fully describing the protocol of the T C P connection and all of them. First, we define class TCPConnection, which provides an interface to transmit data and handles a request for changing states. 2 0 4 Design mode: can be used for object-oriented software

This example is based on the T c P connection protocol described by LY N C H and R O S E [L R 9 3]. T C P C O N E C T I O N Maintained an example of a T c P S t a t-class in a member variable of the _ S t a t e. The class T C P S t a t e copies the state change interface of T C P C O N E C T I O N. Each T C P S t a T E operation is used as a parameter in an example of a T C P C O N E C T I O N, so that the T C P S T A TE can accesses the data in T C P C O N e C T I O N and the state of changing the connection. T C P c O N n E C T I O N delegates all of the state-related requests to its T c P S t a t e instance _ S t a t e. T C P C O N n E C T I O N also provides an operation to set this variable to a new T c P S T A TE. The constructor of T C P C O N e C T I O N initials the state object to T C P L O S E D state (defined later). Chapter 5 Behavior Mode 2 0 5T C P S t A TE E achieve a default behavior for all delegated requests. It can also call C H a ​​N g e S t a t-operation to change the state of T C P C O N e C T I O N. T C P S t a t e is defined as the privilege of T C P C O N e C T I O N, thereby giving it the privilege of this operation. The subclass of T C P S t a t e EE is implemented with the status. A T c P connection can be in a variety of states: established, listening, closed, etc., has a subclass of T C P S t a t e for each state. We will discuss three subcategories in detail: T C P E S T a B L I S HE E D, T C P L I S E N and T C L O S E D. The subclass of T C P S t a t e has no local state, so they can be shared, and each subclass is only one instance. The unique example of each T C P S t a T E E subclass is operated by a static I N S T a N C e. Each T C P S t a t e subs class is a legal request implementation and a particular state-related behavior: 2 0 6 Design mode: the basis for object-oriented software

This makes each T C P S t a T e sub-class into one S I N G L E T O N (see S i N g L e t o n). After completing the state-related work, these operations call CH A N g e S t a T E operation to change the state of T C P C O N E C T I O N. T C P C O N n E C T I O N It does not know anything to the T C P connection protocol; it is defined by the T c P S t a t e subclass to define each of the state transitions and operations in T C P. 11. It is known to apply J O H N S O N and Z W E I G [J Z 9 1] describe the application of S T A T E and its application on the T C P connection protocol. Most popular interactive drawing programs provide "tools" that work in a direct manipulation. For example, a straight line tool allows you to create a new straight line with via a household click and drag; a selection tool allows the user to select a graphic object. There are usually a lot such tools placed on a option board for user selection. Users think this activity is to select a tool and use it, but the behavior of the editor changes with the current tool: When a drawing tool is activated, we create a graphic object; when the tool is activated, we choose graphics Object; etc. We can use the S t a t e mode to change the behavior of the editor according to the current tool. We can define an abstract To O L, and then derive some subclasses from this class to achieve behavior related to specific tools. The graphic editor maintains a current To O L object and entrusts the request to it. When a user selects a new tool, this tool object is replaced with new, so that the behavior of the graphic editor changes accordingly. This technology is used in the drawing editor framework in H O T D R A W [J O H 9 2] and U N i D R A W [V L 9 0]. It makes customers easily define new types of tools. In H O T D R A W, the DrawingController class forwards the request to the current To O L object. In U N i D R A W, the corresponding classes are VI E W E R and TO O L. The interface on the top page is simple to describe the interface of TO O L and D R A W I N G C O N T R O L1. The envelope-letter idom [COP92] of C O P L I e n is also related to the S t a t e mode. Envelope-letter is a technique for changing a class of an object at runtime. The S t a t e mode is more special, which is focused on how to deal with objects that changes in behavior changes with status. 12. Related Mode F L Y W E I G H T Mode (4. 6) Explain when and how to share status objects. The status object is usually S i N g L E T O n (3. 5). Chapter 5 Behavior Model 2 0 7

5.9 Strategy - Object Behavior Model 1. It is intended to define a series of algorithms to encaps them one by one, and make them replace each other. This mode makes the algorithm can be varied independently of its customers. 2. Alias ​​policy (P O L i C Y) 3. Motivation has a number of algorithms to branch a positive flow. It is not advisable to use these algorithms to use their classes, whose reasons are as follows: • Clients that need to be wrapped • If you directly contain change algorithm code, it will become complicated, which makes the client program huge and difficult to maintain, especially The problem will be more serious when it needs to support a variety of wrap algorithms. • Different algorithms need to be supported when we don't want to support our wire feed algorithms. • When the wrap function is a difficult-to-split component of the client, add a new wrap algorithm or change the existing algorithm. We can define some classes to encapsulate different wrap algorithms to avoid these issues. A algorithm in this method is referred to as a strategy (S T R A T E G Y), as shown below. Suppose a C O m P O S i t i O N class is responsible for maintaining and updating the text of the text displayed in a body browse program. The wrap strategy is not implemented by the C O m P O S I t I O N, but is independently implemented by the subclass of the abstract C O M P O S i T O R class. C O m P O S i t O r Each subclass implementation different lineline strategies: • S i m p L E C O m P O S i t o R enables a simple policy, which determines a wrap location once. • TE X C O M P O S i T O R Implements the TE E X Algorithm for Finding the Wrap Location. This strategy is trying to optimize the wrap, that is, handle a paragraph of a paragraph. • ArrayCompositor implements a policy that makes each line contain a fixed number of items. For example, use 2 0 8 design mode: can be used for object-oriented software

Branches on a range of icons. C O m P O S i Ti N Maintains a reference to the C O m P O S i t o R object. Once C O m P O S i t I o N reforms its body, it forwards the responsibilities to its C O m P O S i t o R object. CO O M P O S I T I O N Customer Specifies which C O m P O S i t O R should be used to directly hold the C O m P O S I t O R it we want into C O m P O S I Ti ON. 4. Applicability When there is the following cases, the S T R a T E G Y mode • Many related classes are only different. "Policy" provides a method of configuring a class with a behavior in multiple behaviors. • Different variants of an algorithm are required. For example, you may define some algorithms that reflect different space / time weigh. When these variants are implemented as a class level of an algorithm [H O 8 7], policy mode can be used. • 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. • A class defines a variety of behaviors, and these behaviors appear in the form of multiple conditional statements in this type of operation. External conditional branches into their respective S T R A T E G Y classes instead of these conditional statements. 5. Structure 6. Participants • S T R A T E G Y (Policy, such as C O M P O S i R) - Define all supported algorithms of common interfaces. C O N t e x T uses this interface to call an algorithm for definition of a C O N C R e t e s T R A T E G y. • C O N C R e t e S T R A T E G Y (Specific Strategy, such as S i M P L E C O M P O S I T O R, TE X C O M P O S I T O R, ArrayCompositor) - A specific algorithm is implemented in the S T ROMPOMPOSIS. • C O N t e x t (context, such as C O m P O S I T) - configured with a C O N C R e t e S R A T E G Y object. Maintaining a reference to the S T R a T E G Y object. - A interface can be defined to let S t a t e g y access its data. 7. Collaboration • S T R A T E G Y and C O N T E X T Interaction To implement the selected algorithm. When the algorithm is called, Context can pass all the data required by the algorithm to the S t a t e g y. Alternatively, C O N t e x t can transmit itself as a parameter to the S T R A T E G Y operation. This allows S t R A T E G Y to call up C O N TE E X T when needed. • C O N t e x T forwards its client's request to its S t R A T E G Y. Customers typically create and deliver a C O N C R E TET E S T R A T E G Y object to the C O N t e x t; thus, the customer is only interacting with C O N t e x T. There is usually a series of C O N C R e t e s T R A T E G Y class available to customers. Chapter 5 Behavior 2 0 9

8. Effects S TR a TEME mode has some of the advantages and disadvantages: 1) Related Algorithm Series S T R A T E G Y class level defines a series of reused algorithms or behaviors for C O N t e x T. Inheritance helps to precisely take out the public function in these algorithms. 2) A method inheritance of an alternative inheritance provides another method that supports multiple algorithms or behaviors. You can generate a subclass of C O N TEEx T class to give it a different behavior. However, this will be prepared in C O N TE E X T, and the implementation of the algorithm is mixed with the implementation of C O N T E X T, so that C O N T E X T is difficult to understand, difficult to maintain and difficult to expand, and it is not possible to dynamically change the algorithm. Finally, you get a bunch of related classes, the only difference between them is the algorithm or behavior they use. Encaps the algorithm in a separate S T R a T E G y class, allow you to change it independently of its C O N t e x t, make it easy to switch, easy to understand, and easy to expand. 3) Eliminating some of the conditional statements S T R A T E G Y mode provides another option other than the required behavior required. When different behaviors are stacked in a class, it is difficult to avoid using conditional statements to select the appropriate behavior. These conditional statements are eliminated in a separate S T RE E G Y class. For example, the code without S T R A T E G Y, the body is wrap may be like the S TR a t e G Y mode to eliminate these C A T E G Y objects to eliminate these C A S E-statements: code containing many conditional statements generally means using S T R A T E G Y mode. 4) The selection of the implementation S T R A T E G Y mode provides the same behavior. Customers can choose from different strategies based on different time / spatial trade-offs. 5) Customers must understand that different Strategy this mode has a potential shortcomings, that is, a customer wants to select a suitable S T R a TE E G y must know what these S T R A T E g Y is different. It may have to expose the specific implementation problem to customers. Therefore, only the S T R A T E G Y mode is required only when these different behavior variants are related to the customer. 6) Communication overhead between S T R A T E G Y and C O N TE E-TE E-T E-TE E SET EST R A T E G Y is simple or complex, and they share the interfaces defined by S T R A T E G Y. It is therefore very likely that certain C O N C R e t e s T R A T E G Y will not use information passed to them through this interface; simple C O N c R e t e s T r a t e g Y may not use any of the information! This means that sometimes C O N t e x T creates and initializes some parameters that never use. If there is such a problem, it will need to be more closely coupled between S T R A T E G Y and C O N TEx. 7) Increase the number of objects S T R A T E G y adds the number of objects in an application. Sometimes you can reduce the S T R A T E G Y to reduce this open pin. Any remaining state is maintained by C O N t e x T. 2 1 0 Design mode: can be used for object-oriented software

C O N t e x t passes this state in the request of the S T R A T E G Y object. The shared S t R a g e y should not maintain a state between each call. F L Y W E I G H T (4. 6) The mode describes this method in more detail. 9. Implementation of the following implementation issues: 1) Define the S t R A T E G Y and C O N TE E G Y and C O N TE ES T R A TET E G Y can effectively access any of the data in the C O N t e x T it needs, and vice versa. One way is to let C O N t e x T transmit data to S T R a T E G Y operation in parameters - that is, send data to S T R A T E G Y. This makes S T R a T E G Y and C O N t e x T decoupled. On the other hand, C O N t e x t may send some data not needed by S T R a T E G Y. Another way is to let C O N T E X T pass it as a parameter to S T R A T E G Y, which requests data to the C O N t e x T. Alternatively, S T R A T E G Y can store a reference to its C O N t e x T, which no longer needs to pass anything. In both cases, both S T R A T E G Y can request the data it needs. But now C O N TETETET must define a more fine interface to define its data, which is closerly coupled together with S T R A T E G Y and C O N TET. 2) Use the S t R A T E G y as the template parameter in C , and a template mechanism can be utilized to configure a class with a S T R A T E G y. However, this technique can only be used when the following conditions can be satisfied (1) to select S T R a T E G Y (2) when compiling it does not need to change at runtime. In this case, the class to be configured (e.g., c ontext) is defined as a template class as a parameter in a S Trategy class: When it is alive, this class is configured with a template: use Template It is no longer necessary to define an abstract class to the S Trategy definition interface. As a template parameter, the S T R A T E G Y is also staticly bound to its C O N t e x t, thereby increasing efficiency. 3) Because the S T R A T E G Y object is optionally optionally, even if the additional S T RO is not used, C O N t e x t also meaningful, then it can also be simplified. C O n t e x t Only checking if it exists, if there is, then use it; if not, C O N TE E X T performs default behavior. The advantage of this method is that the customer does not need to handle S T R A T E G Y object unless they don't like the default behavior. 10. Code Example We will give the high-level code for an example of the proceedings, which is based on the implementation of C O M P O S I t I O N and C O M P O S I T O R in I N T E R VI W S [L C i 9 2]. C O m P O S i T I O N-class Maintains a collection of C O m P O N e N T instance, which represents the body and graphic elements in a document. C O m P O S i T i O N uses a C O m P O S i t O R subclass example encapsulated a branch policy to arrange the C O m p o n e n t object into rows. Each C O m P O N e n t has a corresponding normal size, stretchability, and contraction.

Stretchability defines the degree of CO M P O N e N t to grow to the normal size; the contraction defines the degree of contraction. C O m P O S i T i O N passes these values ​​Chapter 5 Behavior mode 2 1 1 to a C O m P O S i T O R, which uses these values ​​to determine the best position of the wrap. When a new layout is required, C O m P O S I t i o n makes it in the CO M P O S I t o R to change. C O m P O S i t O n is transmitted to the three arrays of C O m P O S i t O R, which defines the normal size, stretchability, and contraction of each C O m P O N e N t. It also transmits the number of C O m P O N e N t, the width of the line, and an array, allowing C O m P O S i t o R to populate the position of each wrap. C O m P O S i T O R Returns the number of wraps obtained. The C O m P O S i t O R interface allows C O M P O S I T O N to pass to C O m P O S i t O r all it needs. Here is an example of "transmitting data to S T R a T E G Y": Note C O M P O S i T OR is an abstract class, and its specific subclass defines a particular line of changing strategy. C O m P O S I t I o N is called its C O m P O S i t O r in its R e P A I R operation. R E P A I r first employs the normal size, expandability, and contracted initial array of each C O m P O N e N t (slightly detail). Then it calls C O m P O S i t o r to get a wrap location and finally layout C O m p o n n (also omitted): Now let's take a look at each C O m P O S I t O R subclass. S i m p L E C O m P O S i t O r Checks a row of C O m p o n e n t, and determines the design mode in 2 1 2: the basis for object-oriented software

There is a wrap: TE X C O M P O S i t O R uses a more global policy. Each time it checks a paragraph (P A R A G R A P H) and considers the size and stretching of each C O m P O N e n t. It also passes through the blanks between C O m P O N e n t to try to give this paragraph a uniform "color". A r r a y c o m P O S i t O R Split the member into a row with a rule. These classes do not use all information delivered to C O M P O S E. S i m p L E C O m P O S I t O r ignores the stretchibility of C O m P O N e n t, only considering their normal size; TE X C O M P O S i t O R uses all of the information transmitted to it; and A r r a y c o m P O S i t O r ignores all information. When instances of C O m P O S i t i o n, the C O m P O S i t O r that you want to use is required to: C O m P O S i t O R The interface must be carefully designed to support all typesetting algorithms that the subclasses may be implemented. You don't want to modify this interface in generating a new subclass because it needs to modify other existing subclasses. In general, the interface of S T R a T E G Y and C O N T E X T determines how much the mode can be achieved to a certain extent. 11. It is known to apply E T [W G M 8 8] and I N t e R VI E W S to encapsulate different backlink algorithms. In the RT L system [J M L 9 2] for compiler code optimization, S T R A T E G Y defines different register allocation schemes (R E G I S e R A L O C A T O R) and the instruction set adjustment strategy (R I S C HE E D U L E R, C I S C HE E D U L E R). This provides the flexibility required for optimizing procedures on different target machine structures. Chapter 5 Behavior Model 2 1 3

E T S W A P S m a n a g e r Calculate the engine frame for different financial equipment [E g 9 2]. Its key abstraction is I N S T R u m e n t (devices) and YI E L D C U R V E (beneficial curve). Different devices are implemented as different I n s t r u m e n T subclasses. Yi E L D C U R V. Calculation Factor (discount factors) represents the value of future cash flow. These two classes will delegate some behaviors to the S T R a T E G Y object. The frame provides a range of C O N C R E TET E S T R A T E G Y: The framework is used to generate cash flow, value exchange, and calculating fractures. I N S T R u m E N T and YI E L D C U R and YI E L D C U R can be used to create a new computing engine with different C O N C R e t e s t r. This approach supports mixing and matching existing S TR a T E G Y implementations, also supports the definition of new S T R a T E G Y implementation. B O O CH member [B V 9 0] uses S T R A T E G Y as a template parameter. The B O O c H set class supports three different storage allocation strategies: managed (assigning from a storage pool), controlled (allocated / deserved with lock protection), and no management (normal storage dispenser). When instantiated in a collection class, the S T R A T E G Y is passed to it as a template parameter. For example, an U N b O U N d E d C O L1-free manifold is instantiated as u N b O U N D E D C O L E C T I O N . R a pp is an integrated circuit layout system [g A 8 9, A g 9 0]. R A P P must lay out and wiring the lines of each subsystem in the connection circuit. The wiring algorithm in R a P P is defined as a subclass of an abstract R O U TEE R class. R O U T E R is a S T R A T E G Y class. The O B J E C T Wi N D O W S [B O R 9 4] in the dialog box is used in the dialog box to ensure that the user inputs the legal data. For example, numbers must be within a range, and a numeric input domain should only accept numbers. Verifying a string is the right thing that may need to look for a table. O B J E C T Wi N D O W S Pack the verification strategy using the VA L i D A T O R object. VA L i D A T O R is an example of the S T R a T E G Y object. The data input domain will delegate the verification policy to an optional VA L i D A T O R object. If you need to verify, the customer adds a verifier (an example of an optional policy) to the domain. When the dialog is turned off, the input field allows them to verify the data. This class provides some verifiers for common conditions, such as R A N g e Va L I d A T O R, which numbers. The new verification strategy related to the customer can be easily defined by inheriting VA L i D A T O R. 12. Related Mode F L Y W E I G H T (4. 6): S T R A T E G Y object is often a good lightweight object. 5.10 Template Method (Template Method) - Class behavior mode 1. It is intended to define the skeleton of the algorithm in an operation, and delay some steps into the subclass. TE M P L A T E M e T H O D can redefine certain specific steps of the algorithm without changing the structure of an algorithm. 2. Motivation Consider an application framework for providing A P P L I c a t i O n and D O c u m e n T classes.

A P P L I C A T I O N class is responsible for opening an existing document stored in an externally, such as a file. Once the information in one document is read from the file, it is represented by a D O C U m e n T object. The application constructed with frame can meet specific needs by inheriting A p L i c a t i o n and d o c u m e n t. For example, a drawing application defines D R A W a p L I c a T I O N and D R A W D O C U m E n T subclass; an electronic table application definitions S P R E A D S HE E E E T - A Pl I C A T I O N and S P R E N T Sub-class, as shown in the following page. Abstract A PPLICATION class defines an algorithm that opens and read a document in its o Pen D Ocument: 2 1 4 Design mode: You can use the foundation of object-oriented software O Pen D Ocument defines every document. One main step. It checks whether the document can be opened, create D O C U m e n t objects related to the application, add it to its document collection, and read the D O C u m e N t from one file. We call O P e n d o c u m e n t as a template method. A template method defines an algorithm with some abstract operations, while the subclass will redefine these operations to provide specific behavior. A Subclass of A P P L I C A T I O N will define whether a document can be opened (C A N o P E N D O C U m E N T) and the specific algorithm step of creating documents (D O C R E A T E D O C U m E N T). D O c u m e n T subclasses will define an algorithm step of the read document (D O R E A D). If desired, the template method can also define an operation (A B O U T TO O P E N D O C U m E N T) Let the A P P L I C A Ti O N Sub-class know when the document will be opened. By defining some of the steps in an algorithm using abstract operations, the template method determines their order, but it allows A P P L I C A T I O N and D O C U m E n T subclasses to change these specific steps to meet their respective needs. 3. Applicability Template Method Apply to the following: • Distribute the constant portion of an algorithm in one time, and leave a variable behavior to subclasses. • Public behavior in each subclass should be extracted and concentrated into a public parent class to avoid code repetition. This is a good example of "heavy decomposition" described by O P D Y K E and J O H N S O N [O J 9 3]. First identify the differences in the existing code and separately separate from the new operation. Finally, these different code is replaced with a template method that calls these new operations. • Control subclass extension. The template method only calls the "H O K" operation at a particular point (see the effect section), which allows only to expand these points. 4. Structure (see page chart) 5. Participants • A Bstract C LASS (abstract class, such as a PPLICATION) - Define Abstract Operations (Primitive Operation), the specific subclasses will redefine them to implement one algorithm Chapter 5 Behavior 2 1 5

Each step. - Implement a template method to define the skeleton of an algorithm. This template method not only calls the original language operation, but also invokes the operation defined in the A b S T R A C T C L A S or other object. • C O N C R e t E C L A S (for specific classes, such as M Y a P L I C A T I O N) - Implementing the primitive operation to complete the steps associated with a particular subclock in the algorithm. 6. Collaboration • ConcreteClass relysses the steps of the algorithm in the algorithm by A B S T R A C T C L A S s. 7. Effect template method is the basic technology of code multiplexing. They are especially important in class libraries, and they extract public behavior in the class library. The template method leads to a reverse control structure, which is sometimes referred to as "Hollywood", ie "Don't find us, we look for you" [s W E 8 5]. This refers to a parent class to call a subclass of operation, not the opposite. Template method calls the following types of operations: • Specific operation (C O N C R e t e c L A S S or the operation of the customer class). • The operation of the specific A B S T R A C T C L A S S (ie, the operation of the child is usually pair). • The primitive operation (ie, abstract operation). • Factory Method (see Factory Method (3. 5)). • Hook Operations, which provides default behaviors, and subclasses can be extended when necessary. A hook operation is usually an air operation in the default operation. It is important to indicate that the template method should indicate which operations are hook operations (which can be redecided) and which is an abstract operation (must be redefined). To reuse an abstract class effectively, subclass writing must clear what operations are designed to be defined. Subclasses can expand the behavior of the operation by redefining the operation of the parent class, and the parent class operation can be explicitly adjusted. Unfortunately, people can easily forget to call the inherited behavior. We can convert such an operation into a template method to control the parent class to control the scope of the subclass. That is, the hook operation is called in the template method of the parent class. Subclasses can redefine this hook operation: 2 1 6 Design mode: can be used for object-oriented software

P at the HOOK O Perb itself: Subclass redefines the HOOK O Peration to extend its behavior: 8. Implementing three implementation problems worth noting: 1) Use C Access Control in C The primitive operation of a template method call can be defined as a protection member. This ensures that they are only called by template methods. The primitive operation that must be redefined must be defined as a pure virtual function. The template method itself does not need to be redefined; therefore, the template method can be defined as a non-virtual member function. 2) To minimize an important purpose of the primitive operation Definition Template method is to minimize the number of primitive operations that must be redefined when the algorithm is implemented. The more you need to redefine, the more you get the customer program. 3) Naming conventions can add a prefix to identify them with the names that should be redefined. For example, M AC A PP framework for m acintosh applications [A PP 8 9] to template method plus "D O -", such as "D O C Reate D Ocument", "D O R EAD", etc. . 9. Code Example The following C instance illustrates how a parent class enforces its subclasses to follow a constant structure. This example comes from the a p p K i t [A D D 9 4] of N e x T. Consider a class VI e w that supports drawing on the screen. A view can set a suitable specific drawing status (such as color and font) when entering the "F O C U S) state, so that only the drawing can only be drawn after" focus ". VI E W Class Forced its subclasses to follow this rule. We use the D I S P L a Y template method to solve this problem. VI e w defines two specific operations, S e t f O c u s and R e t f O c u s, set and clear the plot state, respectively. The D O D I S P L a Y hook operation of VI E W implements a real drawing function. D i s p1 Y is called SE t f O c u s to set the plot state before D O D i S P1, to set the plot status; D i s p1 is then called R E S E T F O C u s to release the plot state. To maintain the constant portion, the client of VI E W typically calls D i S P L a y, and the subclass of VI E W typically redefines D O D i s P L a y. VI E W itself D O D i S P L a y is nothing: Subclasses redefine it to increase their specific drawing behavior: 10. Known application template methods are very basic, they can be found in any abstraction class. Wi R f S - B R o C K et al [W B W 9 0, W B J 9 0] has been well outlined and discussed in the template method. Chapter 5 Behavior 2 1 7

11. Related Mode Factory Method mode (3. 3) is often called by template method. In the example of the moving section, D O C R e a t e d o c u-M e N t is called by a template method O p e n d o c u m e n t. S T R A T E G Y (5. 9): Template Method Use inheritance to change part of the algorithm. The S TR a T E G Y uses the commission to change the entire algorithm. 5.11 Visitor - Object Behavior Model 1. It is intended to represent an operation of each element in an object structure. It allows you to define new operations for these elements without changing the class of each element. 2. Motivation considers a compiler that expands the source program as an abstract syntax tree. This compiler needs to implement some operations on an abstract syntax tree for "static semantic" analysis, such as checking all variables have been defined. It also needs to generate a code. Therefore, it may have to define a number of operations to perform type check, code optimization, process analysis, check whether the variable is assigned before use, and so on. In addition, the abstract syntax tree can be used for a beautiful format printing, program reconstruction, C O D EI N S t R u m e n t i o n, and multiple measures for the program. Most of these operations require different processing for different nodes. For example, the processing of the node representing the assignment statement is different from the processing of the node representing the variable or arithmetic expression. Therefore, there is a class for assigning statements, and there are classes for variable access, as well as an arithmetic expression, and so on. The set of nodes is of course depends on the compiled language, but there is little change in a given language. The above block diagram shows a part of the N O D E class hierarchy. The problem here is that all of these operations can be dispersed into various nodes classes, resulting in difficult to understand, difficult to maintain and modify. Place the type check code and the beautiful format print code or process analysis code will be confusing. In addition, adding new operations typically require recompilation of all these classes. If new operations can be added independently, these nodes are independent of the operations acting on them, it will be better. To achieve the above two objectives, we can pack the operations related to each class in a separate object (called a VI S i T O R) and passed this object to the currently accessed element when traversing the abstract syntax tree. When an element "accepts" the visitor, the element sends a request to the visitor to the request. This request also also uses the element itself as a parameter. Then the visitor will perform this operation for the element - this operation is previously in the class of this element. For example, a compiler that does not use the visitor may pass to call Ty P e c H e c k operation on its abstract syntax tree 2 1 8 design mode: can be used for object-oriented software

A process for type check. Each node will be the TY P E C H E C K that calls its member to realize its own TY P E C H E C K (see the foregoing box diagram). If the compiler uses the visitor to check a process, it will create a TY P E C HE E C K I N G VI S i T O R object, and call a C C E P t on an abstract syntax tree with this object. Each node will call the visitor when implementing the A c c e P t: an assignment node calls the visitor VI S i T A S I g n m e n t operation, and a variable reference will call VI S i t vA R i a b l E R E f E R e n c e. The TY P e C H operation of previous A S S I g N m E N T N o D E is now a VI S I t a S I g n m e n t for TY P E C H E C K I N G VI S I T O R. In order to make the visitor not only only type check, we need all the visits of all abstract syntax trees with an abstract parent class N o D E VI S i t O r. N o D E VI S i T O R must define an operation for each node class. A application that requires a calculation program will define a new subclass of N O D E VI S i T O R and will no longer need to increase the code associated with a particular application in the node class. The VI S i T O R mode encapsulates the operation of each compilation step in a VI S i T O R associated with this step (see the figure below). Using the VI S i T O R mode, two class levels must be defined: an element corresponding to the acceptable element (N O D E Hie) The other correspondence to the action of the operation of the element (N o D e Vi S I t O R). Add a new action to the visitor class level to create a new action. As long as the compiler accepts syntax does not change (ie, we do not need to add new N o D E subclasses), we can simply define new NOD E VI S i T O R subclasses to increase new features. 3. Applicability Use the VI S i T O R mode in the following situations: • An object structure contains many types of objects, which have different interfaces, and you want to implement some of these objects that depend on its specific class. • Need many different and unrelated operations to objects in an object structure, and you want to avoid "pollution" of these objects. VI S i T O r makes you focus on a class in a class. When the object structure is shared by many applications, the VI S i T O R mode allows each application only contains the required operations. • Define the class of object structure rarely change, but often needs to define new operations on this structure. Change the object structure, Chapter 5, behavior mode 2 1 9

To redefine the interface to all visitors, this may require a lot. If the object structure class changes, it is possible to define these operations in these classes. 4. Structure 5. Participants • VI S i T O R (Accessor, such as N O D E VI S I T O R) - A VI S i T operation is declared for each class of C O N C R e t e e l e m e n t in the object structure. The name and feature of this operation identify the class that sends VI S i T request to the visitor. This allows visitors to determine the specific classes that are being accessed. This visitors can access it directly through the specific interface of this element. • C O N C R E TEE VI S I T O R (Specific Accessor, such as TY P E C HE E C K I N G VI S I T O R) - Implements the operation of each by VI S i t O R declaration. Each operation implements a part of this algorithm, and the algorithm is broken is a class corresponding to the object in the structure. C O N C R e TE E VI S i T O R provides the algorithm with a context and stores its local state. This state is often accumulated in the process of traversing the structure. • E L E M e N t (Element, such as N o D) - Defines a A C C E P T operation, which is parameter in one visitors. • C O N C R E TET E E E E E E M E N T (Specific Elements, such as A S S I g N M E N T N O D E, VA R I A B L E R E F N O D) - A C C E P T operation is implemented, which is parameter as an accessor. • O B J E C T S R u C T U R E (Object Structure, such as P R O G R A M) - can enumerate its element. - A high-level interface can be provided to allow the visitor to access its elements. - can be a compound (see C O m P O S I T E (4. 3)) or a collection, such as a list or a disorderly set. 2 2 0 Design mode: can be used for object-oriented software

6. Collaboration • A customer using VI S i T O R mode must create a C O N C RET E VI S i T O R object, and then traverse the object structure, and use the visitor to access each element. • When an element is accessed, it calls the VI S i t O r operation corresponding to its class. If necessary, the element will use itself as a parameter of this operation so that the visitor accesses its status. The following interaction block diagram illustrates a collaboration between an object structure, an accessient and two elements. 7. Effects The following is some of the advantages and disadvantages of visitors: 1) Accessor mode makes it easy to increase new operational accessers make the operation of increasing components dependent on complex object structures. Just add a new visitors to define a new operation on an object structure. Conversely, if each function is dispersed above multiple classes, you must modify each class when you define a new operation. 2) Accessor concentration related operations and unrelated operationally related behavior is not distributed in various classes that define the object structure, but are concentrated in one visitors. Non-related behavior is placed in their respective visitor subclasses, respectively. This simplifies the class of these elements, and simplifies the algorithms defined in these visits. All data structures associated with its algorithms can be hidden in the visitor. 3) Increasing the new C O N C R e t e E L E M e n T Type VI S i T O R Mode makes it difficult to increase the subclass of the new E L E M e N t. Each addition of a new C O N C R e t E E E E M e n t adds a new abstraction operation in VI S T O R and implements a corresponding operation in each C O N C R e T Vi S i T O R class. Sometimes a default implementation can be provided in VI S i T O R, which can be inherited by most C O N C R e t e VI S I t o, but it is said to be a law is not as follows. So considering the key issue when applying the visitor mode is which portion of the system changes often, is the algorithm acting on the object structure or constitutes the class of each object of the structure. If there is always a new C O N C R e t e L E M e n T, the VI S t O R class level will become difficult to maintain. In this case, these operations may be more easier to define these operations directly in the class constituting the structure. If the E L E M e n T level is stable, and you constantly add operations to modify algorithms, visitors can help you manage these changes. 4) Accessing an iterator through the class level (see I T E R A T O R (5))) can traverse the entire object structure by calling a specific operation of the node object while accessing these objects. But iterators cannot operate on object structures with different element types. For example, the I t e R A T O R interface defined in Chapter 5 can only access the type I t e m: Chapter 5 Behavior 2 2 1

This means that all elements that all the iterators can access have a common parent class I t e m. Visitors do not have this limit. It can access objects that do not have the same parent class. Any type of object can be added to a VI S i t O R interface. For example, M y Ty P e and YO U R Ty P e can be completely independent, and they do not have to inherit the same parent class. 5) Cumulative Status When the visitor accesses each element in the object structure, it may accumulate. If there is no visitors, this state will be passed to the operation of traversal as an additional parameter, or is defined as a global variable. 6) Destroying the package visitor method assumes that the function of the C O N C R e t E E L E M e n T interface is sufficient to allow the visitor to do their work. As a result, this mode often forces you to provide public operations in the internal state of the elements, which may destroy its encapsulation. 8. Implementation of each object structure will have a related VI S i T O R class. This abstract visitor class is operated by each C O N C R e t e E L E M e n t class in which the object structure is defined. The VI S i T operation on each VI S i T O r declares that its parameter is a specific C O N C R E TEE E E E E M E N t to allow the VI S I t O R to directly access the interface of C O N C R e t e E L E M e N t. C O N C R E TE E VI S T O R Demonstrates Each VI S i T operation, thereby implementing behavior related to a particular visitor to the corresponding C O N C R E E E E E M e n T. In C , the VI S i T O R can be defined in this way: each C O N C R e TET EE L E M e n T operation is implemented, which corresponds to the VI S I t of the CO N C R e t E E L E M E N T...................... This finally obtained operations not only depends on the class of the element, but also depends on the class of the visitor. The specific element is declared: 2 2 2 Design mode: can be used for object-oriented software

Because the parameters transmitted by these operations are different, we can use the function overload mechanism to give these operations to the same simple naming, such as VI S i t. This overload is also good. On the one hand, it emphasizes the fact that each operation is the same analysis, although they use different parameters. On the other hand, for those who read code, it is not so obvious that the call point is doing. In fact, this ultimately depends on whether the function's overload mechanism is good or bad. One C OMPOSITE E LEMENT class may be like this to implement a ccept: The following is the other two implementations generated when applying the VI SITOR mode: 1) Dual Distribution (D OUBLE - DISPATCH) visitor mode allows you to do not change the class Increase the operation thereon. In order to achieve this effect, a technique called double dispatch (D O U B L E - D I S P A T C H) is used. This is a very famous technology. In fact, some programming languages ​​do even support this technology (for example, C L O). Language supports singularity (S i N g l E - D I S P a T C H). In the single-assisted language, it is possible to implement a request from two aspects: the name of the request and the type of recipient. For example, a G e n e r a t e C O D e-request will determine the type of operation that will be called to the type of node object you requested. In C , a VA R I A B L E R e f N o DE instance call g e n e-t e c O D E will call VA R i a b L E R e f N o D: g e n e r a t e c O d E (which generates a variable referenced by code). The GE N E R A T E C O D E, which calls A S S I g N M e N t N o D e, will call A S I g n m e n t:: g e n e t e C O D e (which generates a coded code). So which operation is finally implemented in two aspects of the type of request and recipient. Dual Distribution means that the operation is performed determines the type of request and the type of two recipients. A C C E P T is a D O U B L E - D I S P A T C H. Its meaning is determined in two types: VI S i t O r Type and the type of E L e m e n t. Dual distribution makes the visitor to request different operations for each type of element. This is the key to the VI S i T O R mode: The resulting operation not only determines the type of the VI S i T O R and the type of E L E M e N T it accesses. You may not be static in the E L E M e n t interface, and place it in a VI S i t O r, and Chapter 5 Behavior mode 2 2 3

If we can have a pair, why can't you be a three-party or quadrite, or even any other number of dispatosition? In fact, the double dispatch is only a special case of multi-dispersion (M u L T I P L E-D I S P A T C H), and the selection operation in the multi-assignment is based on any number of types. (In fact, C L O S supports multi-disperse.) In supporting a language of a pavilion or multiple assignment, the VI S i T O R mode is not so necessary. Use A C C E P t to be binded at runtime. Extending E L E M e n t interface is equal to defining a new VI S i t O R subclass rather than multiple new E L E M e n T subclasses. 2) Who is responsible for traversing an object structure an visitor must access each element of this object structure. The question is, how do it do? We can put the responsibilities of the traverses in any of the three places: in the object structure, in the visitor, or a separate iterator object (see I T E R A T O R (5. 4)). It is usually responsible for iteration by the object structure. A collection requires it to be iterated, and the A c c e P T operation is called for each element. A composite usually allows A C C E P T to operate the sub-components of the element and recatctively call A C C E P T in each of them. Another solution is to use an iterator to access individual elements. In C , you can use an internal iterator or an external iterator. Which one depends on which one is available and which is most effective. In S M A L, in S M A L, an internal iterator is usually used, and this internal iterator uses DO: and a block. Because the internal iterator is implemented by the object structure, use an internal iterator to a large extent like the object structure is responsible for iteration. The main difference is that an internal iterator does not generate a double dispatch - it will use this element to call a parameter to call the visitor's operation instead of an operation of the accesser as a parameter call element. However, if the visitor's operation simply invokes the operation of the element without recursive, the VI S i t o R mode using an internal iterator is easy to use. It can even be placed in the visitor, although this will result in each of the polymerization C O N C R e t e E E E M e N t, and the code is copied in each C O N C R e TEE VI S i t O r. The main reason for placing the traversal strategy in the visitor is to achieve a particularly complex traversal, depending on the results of the operation of the object structure. We will give an example of this situation at the code example. 9. Code example Since the visitor is typically associated with composite, we will use the E Q U I P M e n T class defined in the CO M P O S I T E (4. 3) Code Example Tape to illustrate the VI S I T O R mode. We will use VI S i T O R to define some operations for calculating the total cost of material inventory lists and single device. E Q u i pm e n T class is very simple, in fact, do not have to use VI S i t O r. But we can easily see what it will be involved in implementing this mode. Here is the E q U I P M e n T class in C O m P O S I t e (4. 3). We add a A c c e P T operation to work with an visitor. EQ U I P M e n T Operates the properties of the device, such as its power consumption and price. These operations are appropriately redefined for specific types of devices such as chassis, engine and flat panels. 2 2 4 Design mode: can be used for object-oriented software

As shown below, all the abstract parent classes of all device visits have a virtual function for each device subclass. All default behaviors of all virtual functions do not do. E quipment subclasses define a ccept in substantially the same manner: Call the operation of the E quipment VI Sitor corresponding to the class that accepts a ccept request, such as device containing other devices (especially in c omposite mode C  e quipment Subclasses to implement A ccept, traverse their individual sub-components and call their respective A ccept operations, and then call VI SIT operations. For example, C H A S S I S:: A C C E P T can be like all of the components in the chassis such that E Q U IP M e N T VI S I T O R defines a particular algorithm on the device structure. P R I C I N g VI S i t O r Calculates the price of the device structure. It calculates all simple devices (such as floppy disks) and all composite devices (such as chassis and bus). Chapter 5 Behavior 2 2 5P R I C I N G VI S i T O R Put the total price of all nodes in the device structure. Note P R I C I N G VI S I T O R Selects a suitable pricing policy for a class of devices in a corresponding member function. In addition, we only need to change the P R I c i n g Vi S i T O R class to change the pricing policy of a device structure. We can define such a class that calculate a checklist: I N V E N T O R Y VI S i T O R is a total of each type of device in the object structure. I N V e n t O R Y VI S i t O R Use an I n v e n t O R Y class, and I n v e n t o R Y class defines an interface for increasing the device (hereinafter). Here's how to use I N V E N T O R Y VI S I T O R on a device structure: Now we will explain how to implement the S M A L t a Lk in the I N T E R P R mode (5. 3). Like the above example, this example is very small, VI S i t o r may not bring us a lot of benefits, but it has a good explanation how to use this mode. In addition, it illustrates a situation where iteration is the responsibility of the visitor. The object structure (regular expression) consists of four classes, and they have a C C E P: method, which is a parameter with an visitor. In class S Equency E XPRESSION, Accept: Method is: In class R Epeat E Xpression, Accept: Method Sends a Visit R Epeat message; in class a LTernation e xpression, it sends Visit a LTernation: message; ITERAL E XPRESSION, it sends Visit L Itel: Messages. These four classes must also have access functions that can be used by VI S T O R. For S e q u e n c e x p r e s S I o n These functions are 2 2 6 design modes: the basis for object-oriented software

E X P R E S I O N 1 and E X P R E S I O N 2; these functions for A L T E R N A T I O N e x P R E R N A T I V E 2 and A L T E R N A T I V E 2; for R E P E A TE E X P R E S I O N is R E P E T I T I O N; and the L i t E R A L E X P R E S I O N is C O m P O N e N t. Specific visitor is R E M A T C H i N g Vi S I t O r. Because the traversal algorithms it need are irregular, it is responsible for traversal. Its maximum irregularity is that R E P e a t e x p r e s s I O n To repeat it. RE M a T C H i N g VI S I T O R There is an example variable I n p U t S t a t e. In addition to replacing the parameters of the name I n p U t, the parameters of the name I n P U t, the M a T c h in the expression type class in the I N T E R P RE E R mode is basically the same. They returns the collection of streams that can match the expression to identify the current state. 10. It is known that the S M A L t a l k - 8 0 compiler has a VI S i t O R-class called P R O G R a m N o D e N u m E R A T O R. It is mainly used for algorithms of analyzing source code. It is not used for code generation and beautiful format printing, although it can do this. I R I S i N v e n t o R [S T R 9 3] is a kit for developing a three-dimensional graphics application. I N v e n t O r represents a three-dimensional scene as a hierarchy of a node, and each node represents a geometric object or its properties. Some of the operations such as drawing a scenario or mapping an input event requires this hierarchy in different ways. I N v e n t o r uses visits called "A C T I O N" to do this. An operation of generating images, event processing, query, fill, and determining boundary boxes have their respective visits. In order for increasing new nodes easier, I N V E N t O R is C to implement a dual-distribution scheme. The program depends on the type information of the runtime and a two-dimensional table, which represents the visitor in this two-dimensional table. Function pointers that are brought to the visitor and node class in the table. Chapter 5 Behavior Model 2 2 7

Mark Linton proposed term "VI S I T O R" [L P 9 3] in the Fresco Application to O L K K I T of X Consortium. 11. Related Mode C O M P O S I T E (4. 3): Accessors can be used to operate a target structure defined by the C O M P O S I TE E-mode. I N t e R p R e t e R (5. 3): Accessors can be used to explain. 5.12 Discussion of Behavioral Mode 5.12.1 Changes in Packaging Changes are the subject of many behavioral patterns. These modes define an object in this aspect when a program is characterized. This can cooperate with this object when the other portions of the program depends on this aspect. These modes typically define an abstract class to describe objects that changes these packages, and usually naming in accordance with this object. For example, a S T R a T E G Y object encapsulates an algorithm (S T R A T E G Y (5. 9)). • A S t a t e object encapsulates a status-related behavior (S t a t e (3 0 5)). • A protocol between the M e D i a T O R Object package object (M E D i T A T O R (5)). • An I T ER A T O R Object Package Access and Traverse the Method of Various components in a gathering object (I T E R A T O R (5. 4)). These patterns describe aspects that are likely to change in programs. Most modes have two objects: new objects that encapsulate the features, and existing objects of these new objects. If these modes do not use these modes, the functionality of these new objects will become a difficult part of these existing objects. For example, the code of one S t R A T E G Y may be embedded in its C O N t e x T class, while the code of one S t a t e may be directly implemented in the C O N t e x T class of the state. But not all object behavior patterns are like this segmentation function. For example, CHAIN ​​of Responsibility (5. 1) can handle any number of objects (ie, a chain), and all of these objects may already exist in the system. The duty chain indicates another difference between behavioral mode: not all behavioral modes define static communication relationships between classes. The responsibility chain provides a mechanism for communicating between several variable objects. Other modes involve some objects transmitted as parameters. 5.12.2 Objects These modes are always used as objects that are used as parameters. For example, VI S I T O R (5. 11). A VI S i T O R object is a parameter of a polymorphic A c c e P T operation, which acts on the object of the VI S i T O R object. Although the method used in place of the VI S i T O R mode is to distribute the VI S i t O R code in a class of some object structure, the V i s i t o r has neuttered part of the object it accessed. Other modes define some objects that can be delivered as a token, which will be called later. C O m M A N D (5. 2) and M E M E N T O (5. 6) belong to this. In C O m M A N D, the token represents a request; in M ​​E M e N T O, it represents an internal state in an object at a particular time. In both cases, the token can have a complex internal representation, but the customer will not realize this.

But there are some differences here: Polymorphism 2 2 8 design mode in C O m M A N D: can be used for object-oriented software

This topic also runs through other types of patterns. A B S T R A C T f A C T O R Y (3. 1), B U I L D E R (3. 2) and P R O T O T Y P E (3. 4) have encapsulated information about how objects created. D E C O R A T O R (4. 4) Packaged the responsibility that can be added to an object. B R i D g e (4) A abstraction is separated from it to make them independently change. It is very important because it is a polymorphic operation because the C O m M M M M a N D is performed. Instead, M e m e n t o is very small, so that the memo can only be passed as a value. So it is likely to provide any polymorphisms that do not give it at all. 5.12.3 Communication should be packaged or distributed M E D i a T O R (5. 5) and O B S E R V (5. 7) are moderately competitive modes. The difference between them is that O b S e R v E r distributes communication by introducing O b S E R V ER and S UB J E C T object, and M e D i a t O R object encapsulates communication between other objects. In O b S e R mode, there is no single object to encapsulate a constraint, but must be collapsed by O B S E R V ER and S UB J E C T object to maintain this constraint. The communication mode is determined by the observer and the target connection: a target usually has multiple observes, and sometimes a target is also another observer's goal. The purpose of M E D i a T O R mode is to focus instead of distribution. It will maintain a constraint to place them directly in one intermediaries. We have found that generates a reusable O b S E R V E R and S UB J E C T are easier to generate multiple M E D i a t o r generate. O b S e R V pattern facilitates segmentation and loose coupling between O b S E R V E R and S UB J E C T, and this will generate finer granularity, so that it is more likely to be multiplexed. On the other hand, the communication stream in M ​​e D i a t O r is more readily understood relative to O b S E R V E R. Observers and goals are usually connected soon they are created, and it is difficult to see how they are connected in the program. If you understand O b S E R V mode, you will know that the way the observer and target connection is important, and you also know which connections are looking for. However, the indirectibility introduced by O b S e R v ER mode will still make a system difficult to understand. O bs E R V E R in S M A L T A Lk can be parameterized with a message to access the S UB J E C T, and therefore they have greater reusability compared to O b S e R v E r in C . This makes O B S E R V E R in S M a L t a L K more attractive than M e D i a t O R. So a S m a l t a lk programmer usually uses O b S e R v E R and a C programmer uses M E D i a t O R. 5.12.4 Decoupting the sender and recipient When cooperating with each other, they become interdependent, which may have a negative impact on the hierarchical and reuse of a system. Both commands, observers, intermediaries, and responsible chains involve how to decouple senders and recipients, but they have different trade-offs. Command mode uses a C O m M A N d to define a binding relationship between a sender and a recipient to support decoupling, as shown in the following figure. The C O m M A N d provides a simple interface (i.e., E x E C U t e operation) submitted. Defining connections between senders and recipients in a separate object allows the sender to work with different recipients.

This will decouple the sender with the recipient to make the sender easier to multiplex. In addition, a C O m M a N D object can be multiplexed, and a recipient is parameterized with different senders. Although C O m M A N D describes the implementation of the realization technique of avoiding the generation of generated subclasses, each sender-receiver connection requires a subclass. The observer mode is notified of the change in the target by defining an interface to decouple the sender (target) to the recipient (observer). O b s e r v e r defines a looser than C o m m a n d sender - receiver binding, since there may be a plurality of target viewers, and the number thereof can vary at run time, as shown in FIG. Chapter 5 Behavior Model 2 2 9

转载请注明原文地址:https://www.9cbs.com/read-3350.html

New Post(0)