Bridge模式:将抽象和行为划分开来,各自独立,但能动态的结合。
public abstract class Coffee{
CoffeeImp coffeeImp;
public void setCoffeeImp(){
this.coffeeImp=CoffeeImpSingleton.getTheCoffeeImp();
}
public CoffeeImp getCoffeeImp(){
return this.coffeeImp;
}
public abstract void pourCoffee();
}
public abstract class CoffeeImp{
public abstract void pourCoffeeImp();
}
public class CoffeeImpSingleton{
private static CoffeeImp coffeeImp;
public CoffeeImpSingleton(CoffeeImp coffeeImpIn)
{this.coffeeImp = coffeeImpIn;}
public static CoffeeImp getTheCoffeeImp(){
return coffeeImp;
}
}
public class FragrantCoffeeImp extends CoffeeImp{
FragrantCoffeeImp(){
System.out.println("普通Coffee");
}
public void pourCoffeeImp(){
System.out.println("什么也没加,清香");
}
}
public class MilkCoffeeImp extends CoffeeImp{
MilkCoffeeImp(){
System.out.println("牛奶Coffee");
}
public void pourCoffeeImp(){
System.out.println("加了美味的牛奶");
}
}
public class MediumCoffee extends Coffee{
public MediumCoffee(){
setCoffeeImp();
}
public void pourCoffee(){
System.out.println("中杯");
CoffeeImp coffeeImp=this.getCoffeeImp();
coffeeImp.pourCoffeeImp();
}
}
public class SuperSizeCoffee extends Coffee{
public SuperSizeCoffee(){this.setCoffeeImp();}
public void pourCoffee(){
System.out.println("大杯");
CoffeeImp coffeeImp=this.getCoffeeImp();
coffeeImp.pourCoffeeImp();
}
}
public class Test {
public static void main(String[] args) {
//拿出牛奶
CoffeeImpSingleton coffeeImpSingleton = new CoffeeImpSingleton(new MilkCoffeeImp());
//中杯加奶
MediumCoffee mediumCoffee = new MediumCoffee();
mediumCoffee.pourCoffee();
//大杯加奶
SuperSizeCoffee superSizeCoffee = new SuperSizeCoffee();
superSizeCoffee.pourCoffee();
}
}