Design Patterns - State Patterns

It is proposed that the method is too long and violates the "single responsibility principle" and "open closed principle"    

Definition: Allows to change the behavior of an object when its internal state changes, the object appears to change its class

The main solution is when the conditional expression that controls the state transition of an object is too complex. By transferring the judgment logic of the state to a series of classes representing different states, the complex judgment logic can be simplified

benefit:

Localize the behavior related to a specific state, separate the behavior of different states, and put the behavior related to a specific state into one object. Since all state-related code exists in a concreteState, so by Defining new subclasses makes it easy to add new states and transitions

The state pattern reduces interdependence by distributing various state transition logic into subclasses of State

The state pattern can be considered when the behavior of an object depends on the state, and it must change its behavior at runtime based on the state

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace state mode
{
    class Context
    {
        private State state;
        public Context(State state)
        {
            this.state = state;
        }
        public State State
        {
            get { return state; }
            set
            {
                state = value;
                Console.WriteLine("Current state: " + state.GetType().Name);
            }
        }
        public void Request()
        {
            state.Handle(this);
        }
    }
    abstract class State
    {
        public abstract void Handle(Context context);
    }
    class ConcreteStateA:State
    {
        public override void Handle(Context context)
        {
            context.State = new ConcreteStateB();
        }
    }
    class ConcreteStateB : State
    {
        public override void Handle(Context context)
        {
            context.State = new ConcreteStateA();
        }
    }
    class Program
    {
        static void Main(string[] args)
        {
            Context c = new Context(new ConcreteStateA());
            c.Request();
            c.Request();
            c.Request();
            c.Request();
            c.Request();
            Console.Read();
        }
    }
}



Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=324731157&siteId=291194637