装饰者模式

装饰者模式:动态地将责任附加到对象身上。若要扩展功能,装饰者提供了比继承更有弹性的替代方案。

每个组件都可以单独使用,或者被装饰者包起来使用,装饰者和组件必须是同样的类型 ,也就是有共同的超类,目的是利用继承到达类型匹配。装饰者和组件必须有相同的接口,因为装饰者必须取代被装饰者。java io中就使用了装饰者模式。

       Beverage espresso = new Espresso();
		//没有被装饰的价格
		System.out.println(espresso.getDesciption() + " $" + espresso.cost());

		// 这里是递归一样 一个调用一个 因为有共同的父类 所以直接返回espresso
		espresso = new Mocha(espresso);
		espresso = new Sony(espresso);

看出装饰完后直接用组件的引用指向新的对象。

public abstract class Beverage {
	protected String desciption = "Unknown Beverage";
	
	public String getDesciption() {
		return desciption;
	}

	public void setDesciption(String desciption) {
		this.desciption = desciption;
	}

	public abstract double cost();
}
public abstract class CondimentDecorator extends Beverage{
	
	// 覆盖需要装饰的方法
	public abstract String getDesciption() ;

}
public class Mocha extends CondimentDecorator{

	Beverage beverage;
	
	public Mocha(Beverage beverage) {
		this.beverage = beverage;
	}
	
	public String getDesciption() {
		return beverage.getDesciption() +", Mocha";
	}
	
	@Override
	public double cost() {
		
		return 0.20 + beverage.cost();
	}
	
}
public class Sony extends CondimentDecorator{

	Beverage beverage;
	
	public Sony(Beverage beverage) {
		this.beverage = beverage;
	}
	
	public String getDesciption() {
		return beverage.getDesciption() +", Sony";
	}
	
	@Override
	public double cost() {
		
		return 0.66 + beverage.cost();
	}
	
}
public class Espresso extends Beverage{
	public Espresso() {
		desciption = "Espresso";
		
	}

	@Override
	public double cost() {
		
		return 1.99;
	}
}
public class HouseBlend extends Beverage{

	public  HouseBlend() {
		desciption = "House Blend Coffe";
	}
	
	@Override
	public double cost() {
		return 0.89;
	}

}
public class StarbuzzCoffee {

	public static void main(String[] args) {

		
		Beverage espresso = new Espresso();
		//没有被装饰的价格
		System.out.println(espresso.getDesciption() + " $" + espresso.cost());

		// 这里是递归一样 一个调用一个 因为有共同的父类 所以直接返回espresso
		espresso = new Mocha(espresso);
		espresso = new Sony(espresso);
		
		System.out.println(espresso.getDesciption() + " $" + espresso.cost());

	}

}

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值