状态模式
The State design pattern allows an object to alter its behavior when its internal state changes, The object will appear to change its class.
状态设计模式允许当对象内部状态改变时改变其行为,对象似乎改变了它的类。
UML Class Diagram
State: This is going to be an interface that is used by the Context object. This interface defines the behaviors which are going to be implemented by the child classes in their own way.
ConcreteState: There are going to be concrete classes that implement the State interface and provide the functionalities that will be used by the context. Each concrete state class provides behavior that is applicable to a single state of the Context object.
Context:This is going to be a class that holds a concrete state object that provides the behavior according to its current state. This class is going to be used by the client.
Structure Code in C#
/// <summary> /// The State Interface declares methods that all Concrete State Classes should implement. /// </summary> public interface State { void Handle(Int32 balance); } /// <summary> /// Concrete States implement various behavior, associated with a state of the Context Object. /// </summary> public class ConcreteStateA : State { public void Handle(Int32 balance) { Console.WriteLine($"{typeof(ConcreteStateA).Name} handle method."); } } /// <summary> /// Concrete States implement various behavior, associated with a state of the Context Object. /// </summary> public class ConcreteStateB : State { public void Handle(Int32 balance) { Console.WriteLine($"{typeof(ConcreteStateB).Name} handle method."); } }
/// <summary> /// The Context Class defines the interface which is going to be used by the Clients. /// It also maitains a reference to an interface of a State subclasses, whic represents the current state of the Context. /// </summary> public class Context { //A reference to the current state of the Context. private State _state; //The Context Object allows changing the State of the object at runtime. public void Request(Int32 balance) { if (balance > 100) _state = new ConcreteStateA(); else _state = new ConcreteStateB(); _state.Handle(balance); } }
var context = new Context(); context.Request(101); context.Request(99);
When to use State Design Pattern in Real-Time Application?
- We need to change the behavior of an object based on its internal state.
- We need to provide flexibility in assigning requests to handlers.
- An object is becoming more complex with many conditional statement.