码迷,mamicode.com
首页 > 其他好文 > 详细

《大话设计模式》学习笔记12:状态模式

时间:2015-05-17 00:41:14      阅读:161      评论:0      收藏:0      [点我收藏+]

标签:

  技术分享

工作状态示例:

  技术分享

1.State:

    public abstract class State
    {
        public abstract void WriteProgram(Work work);
    }

2.ConcreteState(以ForenoonState、NoonState、SleepingState为例):

    public class ForenoonState:State
    {
        public override void WriteProgram(Work work)
        {
            if(work.Hour<12)
            {
                Console.WriteLine("当前时间:{0} 上午工作,精神百倍", work.Hour);
            }
            else
            {
                work.SetState(new NoonState());
                work.WriteProgram();
            }
        }
    }
    public class NoonState:State
    {
        public override void WriteProgram(Work work)
        {
            if(work.Hour<13)
            {
                Console.WriteLine("当前时间:{0} 饿了,午饭;犯困,午休", work.Hour);
            }
            else
            {
                work.SetState(new AfterNoonState());
                work.WriteProgram();
            }
        }
    }
    public class SleepingState:State
    {
        public override void WriteProgram(Work work)
        {
            Console.WriteLine("当前时间:{0} 太困了,睡着了", work.Hour);
        }
    }

3.Content:

    public class Work
    {
        private State state;
        public Work()
        {
            state = new ForenoonState();
        }
        public int Hour { get; set; }
        public void SetState(State state)
        {
            this.state = state;
        }
        public void WriteProgram()
        {
            state.WriteProgram(this);
        }
    }

4.客户端代码:

    class Program
    {
        static void Main(string[] args)
        {
            Work work = new Work();
            work.Hour = 9;
            work.WriteProgram();
            work.Hour = 12;
            work.WriteProgram();
            work.Hour = 19;
            work.WriteProgram();
        }
    }

 

  状态模式主要解决的是当控制一个对象状态转换的条件表达式过于复杂时的情况。把状态的判断逻辑转移到表示不同状态的一系列类中,可以把复杂的判断逻辑简化。

《大话设计模式》学习笔记12:状态模式

标签:

原文地址:http://www.cnblogs.com/walden1024/p/4508946.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!