Original: C # design mode 18 state pattern ("pattern") "behavioral"
First, Introduction
Today we begin to talk about the sixth mode of the "behavioral" design pattern, which is the "state mode", and the English name is: the status pattern. Whether it is the real world, or the object-oriented OO world, there is a thing inside, that is the object. Of course there is a state of the object. Each object has its corresponding state, and each state has corresponding corresponding behavior, in different states, the way of behavior is not the same. If an object has more than one state, then there will be a lot of corresponding behavior. Then the judgment of these States and the behavior done according to the state result in multiple conditional statements being intertwined, and if you add a new state, you need to change the existing code. Such a design is clearly against the opening and shutting principle, the state pattern is to solve such problems.
Second, the state mode of the detailed introduction
2.1. Motive (motivate)
During the software build process, the behavior of some objects changes as they change, such as when the document is read-only, and the behavior supported by the behavior and read-write status may be completely different.
How can I transparently change the behavior of an object at run time based on the state of the object? Without the introduction of tight coupling between object manipulation and State conversions?
2.2. Intention (Intent)
Allows an object to change its behavior when its internal state changes. This makes the object appear to modify its behavior. --"Design pattern" GoF
2.3. Structure diagram (Structure)
2.4, the composition of the model
As you can see, the structure diagram in the state mode has the following roles:
(1), Environment Role (context): Also called context, defines the interface to which the client is interested, and preserves an instance of a specific State class. An instance of this specific State class gives the existing state of this environment object.
(2), abstract status Role (state): Defines an interface that encapsulates the behavior of a particular state of an environment object.
(3), the specific status role (Concretestate): Each specific State class has implemented a state of the environment (context) corresponding to the behavior.
The role of environment classes and abstract state classes needs to be understood in the state schema structure:
An environment class is actually an object with a state, and the Environment class can sometimes act as the role of the state manager, and you can switch states in the environment class.
abstract State class can be an abstract class or an interface, different state classes are inherited from the different subclasses of the parent class, the state class is generated because the environment class has multiple states, but also satisfies two conditions: these states often need to switch, in different states, the behavior of the object is different. Therefore, the behavior under different objects can be extracted separately and encapsulated in a specific state class, so that the environment class object can change its behavior when its internal state changes, the object seems to modify its class, but actually because of switching to different specific State class implementation. Because the environment class can be set to any specific state class, it is programmed for the abstract state class, which allows the object of any particular State class to be set to the Environment class when the program is run, allowing the environment class to change the internal state and change the behavior.
2.5. Code implementation of State mode
The status mode also has similar examples in the display life, for example: we can check the status of the order in the process of buying the goods online. For the merchant, the order status is different, will allow the customer to have different action requirements, such as: The order is already in the delivery status, this order is not returned. If the order is in the stocking stage, the customer can exchange or return the goods. If our order has been shipped, you are waiting to receive the goods, if the goods have quality problems, you can refuse to sign, or successfully complete the transaction, today we will take the order as an example to illustrate the implementation of the status mode. The implementation code is as follows:
namespaceimplementation of the state mode {//Environment Role---equivalent to the context type Public Sealed classOrder {PrivateState current ; PublicOrder () {//working state initialized to morning work stateCurrent =Newwaitforacceptance (); Iscancel=false; } Private Doubleminute; Public DoubleMinute {Get{returnminute;} Set{minute =value;} } Public BOOLIscancel {Get;Set; } Private BOOLfinish; Public BOOLtaskfinished {Get{returnfinish;} Set{finish =value;} } Public voidSetState (state s) { current=s; } Public voidAction () {current. Process ( This); } } //abstract Status Role---equivalent to state type Public InterfaceState {//Process Orders voidProcess (order order); } //awaiting acceptance – equivalent to a specific status role Public Sealed classWaitforacceptance:state { Public voidProcess (Order order) {System.Console.WriteLine ("We start accepting, ready for stocking! "); if(Order. Minute < -&&order. Iscancel) {System.Console.WriteLine ("you can cancel the order within half an hour! "); Order. SetState (NewCancelorder ()); Order. Taskfinished=true; Order. Action (); } order. SetState (Newacceptanddeliver ()); Order. Taskfinished=false; Order. Action (); } } //handling of shipments---equivalent to specific status roles Public Sealed classAcceptanddeliver:state { Public voidProcess (Order order) {System.Console.WriteLine ("we are ready to ship the goods, we can not cancel the order! "); if(Order. Minute < -&&order. Iscancel) {System.Console.WriteLine ("you can cancel the order within half an hour! "); Order. SetState (NewCancelorder ()); Order. Taskfinished=true; Order. Action (); } if(Order. taskfinished==false) {order. SetState (NewSuccess ()); Order. Action (); } } } //Trading Success---equivalent to a specific status role Public Sealed classSuccess:state { Public voidProcess (Order order) {System.Console.WriteLine ("Order Settlement"); Order. SetState (Newconfirmationreceipt ()); Order. Taskfinished=true; Order. Action (); } } //Confirm Receipt---equivalent status role Public Sealed classConfirmationreceipt:state { Public voidProcess (Order order) {System.Console.WriteLine ("Check the goods, no problem can be signed! "); Order. SetState (Newconfirmationreceipt ()); Order. Taskfinished=true; Order. Action (); } } //canceling an order---equivalent to a specific status role Public Sealed classCancelorder:state { Public voidProcess (Order order) {System.Console.WriteLine ("Check the goods, there is a problem, cancel the order! "); Order. SetState (NewCancelorder ()); Order. Taskfinished=true; Order. Action (); } } Public classClient { Public Static voidMain (string[] args) {//OrderOrder order =NewOrder (); Order. Minute=9; Order. Action (); //can cancel orderOrder. Iscancel =true; Order. Minute= -; Order. Action (); Order. Minute= -; Order. Action (); Order. Minute= +; Order. Action (); Console.read (); } } }
Three, the state mode of implementation points:
The state mode places all the behaviors related to a particular status in a sub-class object in the state, switches the object when the object is switched, but maintains the interface of the State, thus enabling decoupling between the specific operation and the status transition.
Introducing different objects for different states makes the state transitions more explicit and guarantees that there will be no state inconsistencies, because the transitions are atomic-either completely converted or not converted.
If the state object does not have an instance variable, the individual contexts can share the same state object, thereby saving object overhead.
3.1 ", the advantages of state mode
(1), encapsulating the conversion rules.
(2), enumerates the possible states, and needs to determine the kind of state before enumerating the States.
(3), put all the behaviors related to a state into a class, and can easily add new state, only need to change the state of the object to change the behavior of the object.
(4), allows the state transition logic to be integrated with the state object, rather than a large conditional statement block.
(5), you can have multiple environment objects share a state object, thereby reducing the number of objects in the system.
3.2 ", the disadvantage of the state mode
(1), the use of State mode will inevitably increase the number of system classes and objects.
(2), the structure and implementation of State mode are more complex, if improper use will result in program structure and code confusion.
(3), the state mode of the "open and close principle" support is not very good, for the state mode can be toggled state, adding a new state class needs to modify those responsible for the state transformation of the source code, or can not switch to the new state, and modify the behavior of a State class will also need to modify the corresponding class source code.
(3), the state mode can be used in the following cases:
(1), the behavior of an object depends on its state (property) and can change its related behavior depending on its state.
(2), the code contains a large number of object state-related conditional statements, the appearance of these conditions will lead to poor maintainability and flexibility of code, can not easily add and delete state, so that the customer class and the class library coupling enhancement. The behavior of the object is contained in these conditional statements, and these conditions correspond to the various states of the object
Iv. implementation of the. NET State mode
The implementation of the state pattern in net has not been researched thoroughly, if later has the new study content, then adds in. But I feel that this pattern may have a greater use in the business system.
v. Summary
Well, it's written here today. I haven't written anything for a few days because I have a cold recently. Write something today, just write a little slow.
C # design mode 18 state pattern "behavioral"