`

Bridge桥接模式

    博客分类:
  • Java
 
阅读更多

Bridge_Model

 

源码:

 

 

package bridge;

public abstract class Coffee {
	
	@SuppressWarnings("unused")
	private CoffeeImpl coffeeImpl;

	public Coffee(CoffeeImpl _coffeeImpl) {
		this.coffeeImpl = _coffeeImpl;
	}

	//大杯、中杯
	public abstract String pourCoffee();
}
 

 

 

package bridge;

public interface CoffeeImpl {
	
	//加牛奶、不加牛奶
	public String pourCoffeeImpl();
}
 

 

package bridge;

public class MediumCoffee extends Coffee {

	public MediumCoffee(CoffeeImpl _coffeeImpl) {
		super(_coffeeImpl);
	}

	@Override
	public String pourCoffee() {
		return "中杯";
	}
}
 

package bridge;

public class SuperSizeCoffee extends Coffee {

	public SuperSizeCoffee(CoffeeImpl _coffeeImpl) {
		super(_coffeeImpl);
	}
	
	@Override
	public String pourCoffee() {
		return "大杯";
	}
}
 

package bridge;

public class MilkCoffee implements CoffeeImpl {
	
	public String pourCoffeeImpl() {
		return " + 牛奶";
	}
}
 

package bridge;

public class FragrantCoffee implements CoffeeImpl {
	
	public String pourCoffeeImpl() {
		return " ";
	}
}
 

package bridge;

public class Test_coffee {
	public static void main(String[] args) {
		
		// 加牛奶,依次中杯、大杯
		CoffeeImpl milk = new MilkCoffee();
		Coffee milkMediumCoffee = new MediumCoffee(milk);
		System.out.println(milkMediumCoffee.pourCoffee() 
							+ " " 
							+ milk.pourCoffeeImpl());
		Coffee milkSuperSizeCoffee = new SuperSizeCoffee(milk);
		System.out.println(milkSuperSizeCoffee.pourCoffee() 
				+ " " 
				+ milk.pourCoffeeImpl());
		
		// 不加牛奶,依次中杯、大杯
		CoffeeImpl nomilk = new FragrantCoffee();
		Coffee mediumCoffee = new MediumCoffee(milk);
		System.out.println(mediumCoffee.pourCoffee() 
							+ " " 
							+ nomilk.pourCoffeeImpl());
		Coffee superSizeCoffee = new SuperSizeCoffee(milk);
		System.out.println(superSizeCoffee.pourCoffee() 
				+ " " 
				+ nomilk.pourCoffeeImpl());
	}
}
 

结果:

中杯  + 牛奶
大杯  + 牛奶
中杯  
大杯  
 

 

分享到:
评论

相关推荐

Global site tag (gtag.js) - Google Analytics