状态模式

package tutor22;

public class Client {
    public static void main(String args[]){
        Account acc=new Account("ZY",100);
        acc.deposit(500);
        acc.withdraw(300);
        acc.withdraw(400);


    }


}

class Account {


    private AccountState state;


    private String owner;


    public Account(String a,double b){


        owner=a;


        state=new Yellowstate(this,b);


        state.stateCheck();


    }


    public void setsta(AccountState a){


        state=a;


    }


    public void deposit(double a){


        System.out.println(owner+"存"+a+"元");


        state.deposit(a);


        state.stateCheck();


        System.out.println();


    }


    public void withdraw(double a){


        System.out.println(owner+"取"+a+"元");


        state.withdraw(a);


        state.stateCheck();


        System.out.println();


    }


}
abstract class AccountState {


    protected Account acc;


    protected double balance;


    public AccountState(Account a,double b){


        super();


        acc=a;


        balance=b;


    }


    public abstract void stateCheck();


    public void deposit(double amount) {


        balance+=amount;


        System.out.println("存款成功");


        System.out.println("余额为"+balance+"元");


    }


    public void withdraw(double amount) {


        if((balance-amount)>-1000) {


            System.out.println("取钱成功!");


            balance -= amount;


            System.out.println("当前余额:"+balance+"元");


        }else {


            System.out.println("余额不足!");


            System.out.println("当前余额:"+balance+"元");


        }


    }


}
class Greenstate extends AccountState{


    public Greenstate(Account a,double b){


        super(a,b);


    }


    public void stateCheck(){


        if(balance<-1000){


            acc.setsta(new Redstate(acc,balance));


        }else if(balance>=-1000&&balance<0){


            acc.setsta(new Yellowstate(acc,balance));


        }


    }


}
class Redstate extends AccountState {





    public Redstate(Account acc, double balance) {


        super(acc, balance);


    }





    public void stateCheck() {


        if(balance >= -1000 && balance < 0){


            acc.setsta(new Yellowstate(acc, balance));


        }else if(balance >= 0){


            acc.setsta(new Greenstate(acc,balance));


        }


    }


    public void withdraw(double amount) {


        System.out.println("余额不足!");


        System.out.println("当前余额:"+balance);


    }


}
class Yellowstate extends AccountState {





    public Yellowstate(Account acc, double balance) {


        super(acc, balance);


    }





    public void stateCheck() {


        if(balance >=0 ){


            acc.setsta(new Greenstate(acc,balance));


        }else if(balance < -1000){


            acc.setsta(new Redstate(acc,balance));


        }


    }


}

 

posted @ 2021-11-19 18:14  {hunter}ZY  阅读(55)  评论(0编辑  收藏  举报