张德长

导航

设计模式之 State Pattern状态模式

State模式允许对象在内部状态变化时,变更其行为,并修改其类;

优点:

定位指定状态的行为,并且针对不同状态来划分行为,使状态转换显式进行;

适用:

对象的行为依赖于其状态,并且该对象必须在运行时根据其状态修改其行为;

操作具有大量的以及多部分组成的取决于对象状态的条件语句;

 

 /// <summary>
    /// 银行类,白天来银行的是客户,晚上来银行的是窃贼
    /// 根据不同的时间,切换不同的状态,根据不同状态切换类及其行为
    /// </summary>
    public class Bank
    {
        private int hour;
        private Person person;
        /// <summary>
        /// 设置时间,根据不同时间,设定不同状态
        /// </summary>
        /// <param name="hour"></param>
        public void SetClock(int hour)
        {
            this.hour = hour;
            Console.WriteLine($"现在时间是{hour}点");
            if (hour > 8 && hour < 18)
                ChangeState(Customer.GetInstance());
            else ChangeState(Thief.GetInstance());
        }
        /// <summary>
        /// 切换客户状态,使其具有不同的行为
        /// </summary>
        /// <param name="person"></param>
        private void ChangeState(Person person)
        {
            this.person = person;
            person.SayHi();

        }

    }
    /// <summary>
    /// 基类
    /// </summary>
    public interface Person
    {
        void SayHi();

    }
    /// <summary>
    /// 客户类,白天去银行
    /// </summary>
    public class Customer : Person
    {
        /// <summary>
        /// 构造函数私有化
        /// </summary>
        private Customer() { }
        private static Customer customer = new Customer();
        /// <summary>
        /// 单例模式
        /// </summary>
        /// <returns></returns>
        public static Customer GetInstance() => customer;
        public void SayHi()
        {
            Console.WriteLine("我是客户,我来取钱");
        }
    }
    /// <summary>
    /// 窃贼类  ,晚上去银行
    /// </summary>
    public class Thief : Person
    {
        /// <summary>
        /// 构造函数私有化
        /// </summary>
        private Thief() { }
        private static Thief thief = new Thief();
        /// <summary>
        /// 单例模式
        /// </summary>
        /// <returns></returns>
        public static Thief GetInstance() => thief;
        public void SayHi()
        {
            Console.WriteLine("我是窃贼,我来偷钱");
        }
    }
    
        public static void StatePatternTest()
        {
            Bank bank = new Bank();
            int hour = 0;
            while (true)
            {
                bank.SetClock(hour);
                hour++;
                hour %= 24;
                Thread.Sleep(1000);
            }
        
        }

posted on 2023-10-08 15:30  张德长  阅读(5)  评论(0编辑  收藏  举报