首页 > 其他分享 >状态模式

状态模式

时间:2023-06-03 21:48:00浏览次数:24  
标签:状态 object State 模式 class state Context public

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.");
        }
    }
State
  /// <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);
        }
    }
Context
var context = new Context();
context.Request(101);
context.Request(99);
Client

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.

标签:状态,object,State,模式,class,state,Context,public
From: https://www.cnblogs.com/qindy/p/17421083.html

相关文章

  • 享元模式
    TheFlyweightdesignpatternusessharingtosupportlargenumbersoffine-gainedobjectsefficiently.享元模式用共享有效支持大量细粒度的对象。UMLClassDiagram Flyweight:Theflyweightinterfaceenablessharingbutitdoesnotenforceit.Theconcreteobj......
  • 责任链模式
    TheChainofResponsibilitydesignpatternavoidscouplingthesenderoftherequesttoitsreceiverbygivingmorethanoneobjectachancetohandletherequest.Thispatternchainsthereceivingobjectsandpassestherequestalongthechainuntilano......
  • 命令模式
    TheCommanddesignpatternencapsulatesarequestasanobject,therebylettingyouparamizeclientswithdifferentrequests,queueorlogrequests,andsupportundoableoperations.命令模式封装请求作为一个对象,因此让你参数化客户端用不同的requests,队列或者日志r......
  • 解释器模式
    Givealanguage,theInterpreterdesignpatterndefinesarepresentationforitsgrammaralongwithaninterpreterthatusestherepresentationtointerpretsentencesinthelanguage.TheInterpreterDesignPatternprovidesawaytoevaluatelanguagegram......
  • 组合模式
    TheCompositedesignpatterncomposesobjectsintotreestructurestorepresentpart-wholehierarchies.Thispatternletsclientstreatindividualobjectandcompositionsofobjectsuniformly.组合模式将对象组合成tree结构代表部分-整体层次结构,这种模式允许客户......
  • 装饰器模式
    TheDecoratorDesignPatternattachesadditionalresponsibilitiestoanobjectdynamically.Thispatternprovideaflexiblealternativetosubclassingforextendingfunctionality.装饰器模式动态的给Object添加额外的职责,这个模式为SubClassing提供灵活的扩展功能。......
  • 外观模式
    TheFacade designpattenprovidesaunifiedinterfacetoasetofinterfacesinasubsystem.Thispatterndefinesahigher-levelinterfacethatmakesthesubsystemeasiertouse.外观模式为子系统一组接口提供了统一的接口,这种模式定义了高级接口,便于子系统调用。......
  • 适配器模式
    TheAdpativedesignpatternconvertstheinterfaceofaclasstoanotherinterfaceclientsexpect.Thisdesignpatternletsclassesworktogetherthatcouldn'totherwisebecauseofincompatibleinterfaces.适配器模式将类的接口转换为客户期望的另外一个接口,这种......
  • 桥接模式
    TheBridgedesignpatterndecouplesanabstractionfromitsimplementationsothathetwocanvaryindependently.桥接模式将抽象和实现解耦,以便两者可以独立变化。UMLClassDiagram Abstraction:definestheabstraction'sinterface;matainsareferencetoanobj......
  • 模板方法模式
    TheTemplateMethoddesignpatterndefinestheskeletonofanalgorithminanoperation,deferingsomestepstosubclasses.Thispatternletssubclassesredefinecertainstepsofanalgorithmwihoutchangingthealgorithm'sstructure.模板方法设计模式在操作中......