在状态模式中,我们创建表示各种状态的对象和一个行为随着状态对象改变而改变的 context 对象
package org.example.状态模式.软考航空;/*** @author lst* @date 2023年12月07日 15:37*/
class FrequentFlyer {CState state;double flyMiles;public FrequentFlyer() {state = new CNoCustomer();flyMiles = 0;setState(state);}public void setState(CState state) {this.state = state;}public void travel(int miles) {double bonusMiles = state.travel(miles, this);flyMiles = flyMiles + bonusMiles;}
}abstract class CState {public int flyMiles;//里程数public abstract double travel(int miles, FrequentFlyer context);
}//非会员
class CNoCustomer extends CState {@Overridepublic double travel(int miles, FrequentFlyer context) {System.out.println("Your travel will not account for points");return miles;}
}//普卡会员
class CBasic extends CState {@Overridepublic double travel(int miles, FrequentFlyer context) {context.flyMiles += miles; // 将里程数加入到总里程中判断是否升级会员if (context.flyMiles >= 25000 && context.flyMiles < 50000) {context.setState(new CSliver());}if (context.flyMiles >= 50000) {context.setState(new CGold());}context.flyMiles -= miles; // 将里程数恢复return miles;}
}//金卡会员
class CGold extends CState {@Overridepublic double travel(int miles, FrequentFlyer context) {context.flyMiles += miles; // 将里程数加入到总里程中判断是否升级会员if (context.flyMiles >= 25000 && context.flyMiles < 50000) {context.setState(new CSliver());}if (context.flyMiles < 25000) {context.setState(new CBasic());}context.flyMiles -= miles; // 将里程数恢复return miles + 0.5 * miles;}
}class CSliver extends CState {@Overridepublic double travel(int miles, FrequentFlyer context) {context.flyMiles += miles; // 将里程数加入到总里程中判断是否升级会员if (context.flyMiles < 25000) {context.setState(new CBasic());}if (context.flyMiles >= 50000) {context.setState(new CGold());}context.flyMiles -= miles; // 将里程数恢复return miles + 0.25 * miles;}
}class Main {public static void main(String[] args) {// 创建一个 FrequentFlyer 实例,测试银会员50000里程,应该给多少里程FrequentFlyer frequentFlyer = new FrequentFlyer();//本身银会员frequentFlyer.setState(new CSliver());//本年度清零
// frequentFlyer.flyMiles=0;//本年度初始值frequentFlyer.flyMiles=25000;//新增里程数frequentFlyer.travel(25000);displayStatus(frequentFlyer);}// 显示 FrequentFlyer 的会员状态和飞行里程private static void displayStatus(FrequentFlyer frequentFlyer) {System.out.println("Current Member Status: " + frequentFlyer.state.getClass().getSimpleName());System.out.println("Current Fly Miles: " + frequentFlyer.flyMiles);System.out.println("-----------------------------");}
}