咖啡分为大杯咖啡和中杯咖啡,咖啡又分为牛奶咖啡和法式咖啡,java代码实现桥接模式
时间: 2024-05-10 16:20:20 浏览: 82
Java项目源码基于ssm框架的咖啡馆管理系统设计与实现+jsp(完整源码+说明文档+lw).rar
下面是Java代码实现桥接模式:
首先定义一个咖啡接口:
```
public interface Coffee {
void makeCoffee();
}
```
接着定义大杯咖啡和中杯咖啡的实现类:
```
public class LargeCoffee implements Coffee {
private CoffeeAdditives additives;
public LargeCoffee(CoffeeAdditives additives) {
this.additives = additives;
}
@Override
public void makeCoffee() {
System.out.print("制作大杯咖啡 ");
additives.addSomething();
}
}
public class MediumCoffee implements Coffee {
private CoffeeAdditives additives;
public MediumCoffee(CoffeeAdditives additives) {
this.additives = additives;
}
@Override
public void makeCoffee() {
System.out.print("制作中杯咖啡 ");
additives.addSomething();
}
}
```
再定义牛奶咖啡和法式咖啡的实现类:
```
public class MilkCoffeeAdditives implements CoffeeAdditives {
@Override
public void addSomething() {
System.out.println("加入牛奶");
}
}
public class FrenchCoffeeAdditives implements CoffeeAdditives {
@Override
public void addSomething() {
System.out.println("加入法式奶油");
}
}
```
最后,定义一个测试类:
```
public class BridgeTest {
public static void main(String[] args) {
CoffeeAdditives milk = new MilkCoffeeAdditives();
CoffeeAdditives french = new FrenchCoffeeAdditives();
Coffee largeMilkCoffee = new LargeCoffee(milk);
largeMilkCoffee.makeCoffee();
Coffee mediumFrenchCoffee = new MediumCoffee(french);
mediumFrenchCoffee.makeCoffee();
}
}
```
运行结果:
```
制作大杯咖啡 加入牛奶
制作中杯咖啡 加入法式奶油
```
这里使用了桥接模式,将咖啡和咖啡添加物分离开来,使得它们可以独立变化,而不会相互影响。这样可以更加灵活地组合不同的咖啡和添加物,实现不同口味的咖啡。
阅读全文