java工厂模式实现用面向象思想解决饭店会员消费问题,酒店会员分为三个等级:钻石会员,黄金 会员,白银会员。钻石会员享受用餐5折待遇,黄金会员享受7折待遇,白银会员 享受9折待遇,饭店会用一种核算消费的方法计算三种会员的消费
时间: 2023-10-02 16:05:14 浏览: 122
首先,我们需要定义一个会员接口(Member),并在其中定义计算消费的方法(calculateCost):
```
public interface Member {
double calculateCost(double cost);
}
```
接下来,我们需要实现三个会员类,分别是钻石会员(DiamondMember)、黄金会员(GoldMember)和白银会员(SilverMember),它们都实现了会员接口,并根据自身等级提供不同的折扣:
```
public class DiamondMember implements Member {
@Override
public double calculateCost(double cost) {
return cost * 0.5;
}
}
public class GoldMember implements Member {
@Override
public double calculateCost(double cost) {
return cost * 0.7;
}
}
public class SilverMember implements Member {
@Override
public double calculateCost(double cost) {
return cost * 0.9;
}
}
```
最后,我们实现一个工厂类(MemberFactory),根据传入的会员等级参数("diamond"、"gold"、"silver"),返回相应的会员对象:
```
public class MemberFactory {
public static Member createMember(String level) {
switch (level) {
case "diamond":
return new DiamondMember();
case "gold":
return new GoldMember();
case "silver":
return new SilverMember();
default:
throw new IllegalArgumentException("Invalid member level: " + level);
}
}
}
```
现在,我们可以使用工厂类创建不同等级的会员,并调用其计算消费的方法:
```
Member diamondMember = MemberFactory.createMember("diamond");
double diamondCost = diamondMember.calculateCost(100.0); // 消费100元,钻石会员享受5折待遇,实际花费50元
Member goldMember = MemberFactory.createMember("gold");
double goldCost = goldMember.calculateCost(100.0); // 消费100元,黄金会员享受7折待遇,实际花费70元
Member silverMember = MemberFactory.createMember("silver");
double silverCost = silverMember.calculateCost(100.0); // 消费100元,白银会员享受9折待遇,实际花费90元
```
阅读全文