软考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 {
@Override
public double travel(int miles, FrequentFlyer context) {
System.out.println("Your travel will not account for points");
return miles;
}
}
//普卡会员
class CBasic extends CState {
@Override
public 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 {
@Override
public 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 {
@Override
public 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("-----------------------------");
}
}