装饰者模式


Product.java
public interface Product {

	public int money();
}


Coffee.java
public class Coffee implements Product {

	public int money() {
		return 10;
	}

}


Sugar.java
public class Sugar implements Product {

	private Product p; //组合
	
	public Sugar(Product p){
		this.p = p;
	}
	
	public int money() {
		return p.money()+5;
	}

}


Milk.java
public class Milk implements Product {

	private Product p;
	
	public Milk(Product p){
		this.p = p;
	}
	public int money() {
		return p.money()+10;
	}

}


Main.java
public class Main {

	public static void main(String[] args) {

		//咖啡的价格
		Coffee coffee = new Coffee();
		System.out.println(coffee.money());
		
		//加糖咖啡的价格
		Sugar s = new Sugar(coffee);
		System.out.println(s.money());
//		
		//牛奶咖啡的价格
		Milk m = new Milk(coffee);
		System.out.println(m.money());
		
		//牛奶加糖咖啡
		Milk milk = new Milk(new Sugar(new Coffee()));
		System.out.println(milk.money());
	}

}

你可能感兴趣的:(java)