设计模式之装饰模式

一、定义:动态的给一个对象添加一些额外的职责。就增加功能来说,装饰模式相比生成子类更为灵活。Attach additional responsibilites to an object dynamically keeping the same interface. Decorators provide a flexible alternativer to subclass for extending functionallity.

装饰模式在不改变原有类的情况下,继续给该类添加职责,使得装饰后的类,更加适应业务需要。

二、简单代码示例

基础类:

public interface Component {
	void buildWall();
}
public class BuildTheGrateWall implements Component {

	@Override
	public void buildWall() {
		// TODO Auto-generated method stub
		System.out.println("我要调用百万贫民,为我建造万里长城");
	}

}



装饰类:

public class DecoratorWall implements Component {
	private Component component;

	public DecoratorWall(BuildTheGrateWall buildTheGrateWall) {
		// TODO Auto-generated constructor stub
		this.component = buildTheGrateWall;
	}

	@Override
	public void buildWall() {
		// TODO Auto-generated method stub

		selfIntroduction();   //在调用基础类方法之前,添加职责

		component.buildWall(); //不管基类怎么变化,都与我没有关系

		afterBuild();		//调用基础类方法之后,添加职责
	}

	private void selfIntroduction() {
		System.out.println("My name is YinZheng, I am the first tyrant of China, this is my dynasty. I want to"
				+ " unified the China and nerver be invade again");
	}

	private void afterBuild() {
		System.out.println("之后,我要派蒙恬北进,却匈奴七百余里,让胡人不敢南下木马,士不敢弯腰抱怨,君臣固守以安家业");
	}
}
输出:

My name is YinZheng, I am the first tyrant of China, this is my dynasty. I want to unified the China and nerver be invade again
我要调用百万贫民,为我建造万里长城
之后,我要派蒙恬北进,却匈奴七百余里,让胡人不敢南下木马,士不敢弯腰抱怨,君臣固守以安家业


总结:

装饰类和被装饰类可以独立发展,而不会互相耦合。装饰类是继承类的替代方案,用装饰类来代替子类去实现添加职责的行为,而不用暴漏基类给子类,比使用。子类更加灵活。装饰各过程中,避免多层装饰,一层一层的装饰提高了系统的复杂度。




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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值