装饰设计模式

   装饰模式是为了已有功能动态的添加到对象上,它把每个要装饰的功能放在单独的类中,并让这个类包装它所要装饰的对象,以此需要执行特殊行为的时候,客户代码就可以在运行的时候有选择的,按顺序使用装饰类包装对象了。

定义:动态给一个对象添加一些额外的职责,就象在墙上刷油漆.使用Decorator模式相比用生成子类方式达到功能的扩充显得更为灵活。

设计初衷:通常可以使用继承来实现功能的拓展,如果这些需要拓展的功能的种类很繁多,那么势必生成很多子类,增加系统的复杂性,同时,使用继承实现功能拓展,我们必须可预见这些拓展功能,这些功能是编译时就确定了,是静态的。

装饰模式的UML图如下

现在就举个案例使用一下装饰模式

//定义一个对象接口
interface FoodComponent{
	public void process();
	public void setPrice();
}
//具体被装饰对象
class malatang implements FoodComponent{

	public void process() {
		System.out.println("麻辣烫已经煮好了");
	}
	public void setPrice() {
		System.out.println("麻辣烫的价格为1元");
	}
} 

//装饰抽象类,继承HumanComponent,从外部来扩展HumanComponent类的功能
abstract class Decorator implements FoodComponent{
	
	FoodComponent food;
	Decorator(FoodComponent food){
		this.food =food;
	}
	public void process() {
		food.process();
	}
	public void setPrice() {
		food.setPrice();
	}
	
	
}

class Decorator_one extends Decorator{

	Decorator_one(FoodComponent humn) {
		super(humn);
	}

	public void process() {
		super.process();
		System.out.println("麻辣烫加点辣椒");
	}

	public void setPrice() {
		super.setPrice();
	}
}   

class Decorator_two extends Decorator{

	Decorator_two(FoodComponent humn) {
		super(humn);
	}

	public void process() {
		super.process();
		System.out.println("麻辣烫加点香菜");
	}

	public void setPrice() {
		System.out.println("麻辣烫价格涨到2元啦");
	}
}

客户端代码
public static void main(String[] args) {
	  FoodComponent food = new malatang();
	 // food.process();
	  //food.setPrice();
	  Decorator_one one = new Decorator_one(food);
	 // one.process();
	 // one.setPrice();
	  Decorator_two two =new Decorator_two(one);
	  two.process();
	  two.setPrice();
  }




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

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值