java工厂模式用面向象思想解决饭店会员消费问题,酒店会员分为三个等级:钻石会员,黄金 会员,白银会员。钻石会员享受用餐5折待遇,黄金会员享受7折待遇,白银会员 享受9折待遇,饭店会用一种核算消费的方法计算三种会员的消费
时间: 2023-10-01 08:08:21 浏览: 163
首先,我们需要定义一个会员类,包含会员等级和消费金额两个属性:
```java
public class Member {
private String level; // 会员等级
private double consumption; // 消费金额
public Member(String level, double consumption) {
this.level = level;
this.consumption = consumption;
}
public String getLevel() {
return level;
}
public void setLevel(String level) {
this.level = level;
}
public double getConsumption() {
return consumption;
}
public void setConsumption(double consumption) {
this.consumption = consumption;
}
}
```
接下来,我们需要定义一个工厂类,根据会员等级来创建对应的会员对象,并计算消费金额:
```java
public class MemberFactory {
public static Member createMember(String level, double consumption) {
Member member = null;
switch (level) {
case "钻石会员":
member = new DiamondMember(consumption);
break;
case "黄金会员":
member = new GoldMember(consumption);
break;
case "白银会员":
member = new SilverMember(consumption);
break;
default:
break;
}
return member;
}
}
```
然后,我们需要定义三个具体的会员类,分别对应三个不同的会员等级:
```java
public class DiamondMember extends Member {
public DiamondMember(double consumption) {
super("钻石会员", consumption);
}
@Override
public double getConsumption() {
return super.getConsumption() * 0.5;
}
}
public class GoldMember extends Member {
public GoldMember(double consumption) {
super("黄金会员", consumption);
}
@Override
public double getConsumption() {
return super.getConsumption() * 0.7;
}
}
public class SilverMember extends Member {
public SilverMember(double consumption) {
super("白银会员", consumption);
}
@Override
public double getConsumption() {
return super.getConsumption() * 0.9;
}
}
```
最后,我们可以使用工厂类创建不同等级的会员对象,并根据消费金额进行计算:
```java
public class Main {
public static void main(String[] args) {
Member diamondMember = MemberFactory.createMember("钻石会员", 1000);
System.out.println("钻石会员消费:" + diamondMember.getConsumption());
Member goldMember = MemberFactory.createMember("黄金会员", 1000);
System.out.println("黄金会员消费:" + goldMember.getConsumption());
Member silverMember = MemberFactory.createMember("白银会员", 1000);
System.out.println("白银会员消费:" + silverMember.getConsumption());
}
}
```
输出结果为:
```
钻石会员消费:500.0
黄金会员消费:700.0
白银会员消费:900.0
```
以上就是使用面向对象思想解决饭店会员消费问题的工厂模式实现。
阅读全文