【设计模式】17.状态者模式

说明:这个比较简单,使用状态来改变行为,比如有3个行为类,根据条件判断后状态改为某个状态,从而执行这个行为类;

实现:

public class Account
    {
        public ABS_Status status1;
        public double Balance { get { return status1.balance; } }

        public void SaveMoney(double m)
        {
            status1.SaveMoney(m);
        }

        public void Withdraw(double m)
        {
            status1.Withdraw(m);
        }
    }

    public abstract class ABS_Status
    {
        public Account account1 { get; set; }
        public double balance { get; set; }
        public double LowerLimit { get; set; }
        public double UpperLimit { get; set; }

        public abstract void SaveMoney(double num);//存款
        public abstract void Withdraw(double num);//取款
    }

    public class RedStatus : ABS_Status
    {
        //红色状态表示透支,没钱了,不能取款
        public override void SaveMoney (double num)
        {
            balance += num;
            CheckStatus();
        }

        public override void Withdraw(double num)
        {
            //不能取款,所以不做操作
            return;
        }

        public void CheckStatus()
        {
            if(balance > UpperLimit) { 
            //有钱了,转绿色状态,可以取款
            }
        }
    }

    public class GreenStatus : ABS_Status
    {
        //绿色状态表示正常,能取款
        public override void SaveMoney(double num)
        {
            balance += num;
            CheckStatus();
        }

        public override void Withdraw(double num)
        {
            balance -= num;
            CheckStatus();
        }

        public void CheckStatus()
        {
            if (balance < UpperLimit)
            {
                //无钱了,转红色状态,不可以取款
            }
        }
    }

    public class test
    {
        public void start()
        {
            Account aa = new Account();
            aa.SaveMoney(100);
            aa.Withdraw(900);
        }
    }

 

上一篇:通过java编译IDEA方法注释,自动屏蔽groovyScript,实现多线程的封层处理方式


下一篇:Day4-JAVA-设计模式