1.简介
桥接模式,结构型模式,将抽象部分与实现部分分离,使它们都可以独立进行变化。
使用场景:当一个对象要面向多种纬度的时候,就可以用桥接。
2.代码
/**
* 咖啡 的材料
*/
public interface CoffeeStuff {
String addSomething();
}
public class Ordinary implements CoffeeStuff{
@Override
public String addSomething() {
return "原味";
}
}
public class Sugar implements CoffeeStuff{
@Override
public String addSomething() {
return "加糖";
}
}
public abstract class Coffee {
protected CoffeeStuff coffeeStuff;
public Coffee(CoffeeStuff coffeeStuff) {
this.coffeeStuff = coffeeStuff;
}
public abstract void makeCoffee();
}
public class LargeCoffee extends Coffee {
public LargeCoffee(CoffeeStuff coffeeStuff) {
super(coffeeStuff);
}
@Override
public void makeCoffee() {
Log.d(TAG, "makeCoffee: ");
}
private static final String TAG = "LargeCoffee";
}
public class SmallCoffee extends Coffee{
public SmallCoffee(CoffeeStuff coffeeStuff) {
super(coffeeStuff);
}
@Override
public void makeCoffee() {
Log.d(TAG, "makeCoffee: ");
}
private static final String TAG = "SmallCoffee";
}
调用
Sugar sugar = new Sugar();
Ordinary ordinary = new Ordinary();
LargeCoffee largeCoffee = new LargeCoffee(sugar);
SmallCoffee smallCoffee = new SmallCoffee(ordinary);
largeCoffee.makeCoffee();
smallCoffee.makeCoffee();