设计模式—状态模式【Head First 设计模式】
程序员文章站
2022-03-03 09:45:17
状态模式...
状态模式——允许对象在内部状态改变时改变它的行为,对象看起来好像修改了它的类。
类图
关键代码展示
1.State接口
public interface State{
void insertQuarter();
void ejectQuarter();
void turnQuarter();
void dispense();
}
2.状态类
public class NoQuarterState implements State{
GumballMachine GumballMachine;//糖果机的引用
public NoQuarterState(GumballMachine gumballMachine){
this.gumballMachine = gumballMachine;
}
public void insertQuarter(){
System.out.println("You inserted a quarter");
gumballMachine.setState(gumballMachine.getHasQuarterState());//进行了状态的转换
}
//其他方法
}
public class HasQuarterState implements State{
GumballMachine gumballMachine;
public HasQuarterState(GumballMachine gumballMachine){
this.gumballMachine = gumballMachine;
}
public void ejectQuarter(){
System.out.println("Quarter returned");
gumballMachine.setState(gumballMachine.getNoQuarterState());
}
//其他方法
}
public class SoldOutState implements State{};
public class SoldState implements State{};
3.糖果机类
public class GumballMachine{
State soldOutState;
State noQuarterState;
State hasQuarterState;
State soldState;
State state = soldOutState;
int count = 0;
public GumballMachine(int numberGumballs){
soldOutState = new SoldOutState(this);
noQuarterState = new NoQuarterState(this);
hasQuarterState = new HasQuarterState(this);
soldState = new SoldState(this);
this.count = numberGunball;
if(numberGumballs>0){
state = noQuarterState;
}
}
public void insertQuarter(){
state.insertQuarter();
}
public void turnCrank(){
state.turnCrank();
state.dispense();
}
void setState(State state){
this.state = state;
}
//其他方法
}
4.测试类
public class GumballMachineTest{
public static void main(Stringp[] args){
GumballMachine gumballMachine = new GumballMachine(5);
System.out.println(gumballMachine);
gumballMachine.insertQuarter();
gumballMachine.turnCrank();
System.out.println(gumballMachine);
}
}
总结
1.状态模式允许一个对象基于内部状态而拥有不同的行为。
2.Context会将行为委托给当前的状态对象。
3.状态模式和策略模式有相同的类图,但是它们的意图不同:策略模式通常会用行为或算法来配置Context类。状态模式允许Context随着状态的改变而改变行为。
4.状态转换可以由State类或Context类控制。
如有错误欢迎评论指正
本文例子来自《Head First 设计模式》一书,若需要资源可以查看评论区
本文地址:https://blog.csdn.net/Aquaman_/article/details/109632625