我正在尝试学习Java中的继承和接口.我有三个不同的类:Customer,SilverCustomer和GoldCustomer.SilverCustomer和GoldCustomer都扩展了客户.
在申请中,客户获得旅行积分.普通客户获得他们前往积分的里程数.SilverCustomer获得里程*1.5,GoldCustomer获得里程*2分.
当我创建一个普通的客户John时,如何使用方法降级()和升级()在普通客户,silvercustomer和goldcustomer之间切换?
class Testfile {
public static void main(String[] args) {
Airline aProgram = new Airline();
Customer john = new Customer("john", 10001); // 10001 is the id number and the status of a customer is normal
aProgram.addMembers(john);
john.update_mileage(12000);
john.upgrade(); //upgrade John to SilverCustomer
john.update_mileage(2000);
aProgram.printAllCustomerMilege();
}
}
Run Code Online (Sandbox Code Playgroud)
创建对象后,无法更改对象的类.
如果您的逻辑取决于您的客户类型,则可以使用策略设计模式.在您的示例中,您可以编写如下内容:
interface Strategy {
double getMileageCoefficient();
}
class NormalCustomerStrategy implements Strategy {
public double getMileageCoefficient() {
return 1.0;
}
}
class GoldCustomerStrategy implements Strategy {
public double getMileageCoefficient() {
return 2.0;
}
}
在您的Customer类中将有一个私有字段Strategy strategy;
然后您的升级方法将如下所示:
void upgrade() {
this.strategy = new GoldCustomerStrategy();
}
而upgradeMileage方法:
void upgradeMileage(double mileage) {
this.mileage += strategy.getMileageCoefficient() * mileage;
}
归档时间: |
|
查看次数: |
192 次 |
最近记录: |