本文主要是介绍软考2018下午第六题改编逻辑(状态模式),希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!
在状态模式中,我们创建表示各种状态的对象和一个行为随着状态对象改变而改变的 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("-----------------------------");}
}
这篇关于软考2018下午第六题改编逻辑(状态模式)的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!