// 工厂模式
interface CoffeeFactory {
Coffee createCoffee(String coffeeType);
Condiment createCondiment(String condimentType);
}
// 具体工厂类
class ConcreteCoffeeFactory implements CoffeeFactory {
@Override
public Coffee createCoffee(String coffeeType) {
if ("Espresso".equals(coffeeType)) {
return new Espresso();
} else if ("Americano".equals(coffeeType)) {
return new Americano();
} else if ("Latte".equals(coffeeType)) {
return new Latte();
}
return null;
}
@Override
public Condiment createCondiment(String condimentType) {
if ("Milk".equals(condimentType)) {
return new Milk();
} else if ("Foam".equals(condimentType)) {
return new Foam();
} else if ("Syrup".equals(condimentType)) {
return new Syrup();
}
return null;
}
}
// 咖啡类
interface Coffee {
double cost();
}
// 具体咖啡类
class Espresso implements Coffee {
@Override
public double cost() {
return 2.0;
}
}
class Americano implements Coffee {
@Override
public double cost() {
return 2.5;
}
}
class Latte implements Coffee {
@Override
public double cost() {
return 3.0;
}
}
// 装饰者模式
abstract class Condiment implements Coffee {
protected Coffee coffee;
public Condiment(Coffee coffee) {
this.coffee = coffee;
}
}
// 具体装饰者类
class Milk extends Condiment {
public Milk(Coffee coffee) {
super(coffee);
}
@Override
public double cost() {
return coffee.cost() + 0.5;
}
}
class Foam extends Condiment {
public Foam(Coffee coffee) {
super(coffee);
}
@Override
public double cost() {
return coffee.cost() + 0.3;
}
}
class Syrup extends Condiment {
public Syrup(Coffee coffee) {
super(coffee);
}
@Override
public double cost() {
return coffee.cost() + 0.4;
}
}
// 命令模式
interface OrderCommand {
void execute();
}
// 具体命令类
class MakeCoffeeCommand implements OrderCommand {
private Coffee coffee;
public MakeCoffeeCommand(Coffee coffee) {
this.coffee = coffee;
}
@Override
public void execute() {
System.out.println("Making coffee: $" + coffee.cost());
}
}
// 客户端代码
public class CoffeeShop {
public static void main(String[] args) {
CoffeeFactory factory = new ConcreteCoffeeFactory();
Coffee espresso = factory.createCoffee("Espresso");
Coffee americano = factory.createCoffee("Americano");
Coffee latte = factory.createCoffee("Latte");
Condiment milkLatte = factory.createCondiment("Milk")(latte);
Condiment syrupMilkLatte = factory.createCondiment("Syrup")(milkLatte);
OrderCommand[] commands = {
new MakeCoffeeCommand(espresso),
new MakeCoffeeCommand(americano),
new MakeCoffeeCommand(syrupMilkLatte)
};
for (OrderCommand command : commands) {
command.execute();
}
}
}
标签:coffee,return,Coffee,cost,new,123,public
From: https://www.cnblogs.com/Aidan347/p/17874378.html