重拾设计模式-装饰者模式

简介:
装饰者模式属于结构型模式,它的功能是动态地给一个对象添加额外的职责。这种模式比直接生成子类更加灵活。

实现及测试如下

/**
 * 抽象封装
 * @author dedu
 *
 */
public interface Component {
	void operation();
}

/**
 * 实例化的对象,即需要被装饰的本体
 * @author dedu
 *
 */
public class ConcreteComponent implements Component {

	@Override
	public void operation() {
		System.out.println("这是本体操作!");
	}
	 
}

/**
 * 装饰者A进行方式装饰
 * @author dedu
 *
 */
public class ConcreteComponentA extends Decorator {

	public ConcreteComponentA(Component cpt) {
		super(cpt);
	}

	@Override
	public void operation() {
		System.out.println("装饰者A进行方法装饰");
		super.operation();
	}

}

/**
 * 装饰者A进行方式装饰
 * @author dedu
 *
 */
public class ConcreteComponentA extends Decorator {

	public ConcreteComponentA(Component cpt) {
		super(cpt);
	}

	@Override
	public void operation() {
		System.out.println("装饰者A进行方法装饰");
		super.operation();
	}

}

/**
 * 装饰者的父类,对本体类进行了一层封装。具体不同装饰者可重载后做个性化处理
 * @author dedu
 *
 */
public class Decorator implements Component {

	private Component cpt;
	
	public Decorator(Component cpt) {
		super();
		this.cpt = cpt;
	}

	@Override
	public void operation() {
		if (null != cpt) {
			cpt.operation();
		}
	}

}

测试如下

public static void main(String[] args) {
		ConcreteComponent raw = new ConcreteComponent();
		ConcreteComponentA wrapperA = new ConcreteComponentA(raw);
		wrapperA.operation();
		System.out.println();
		ConcreteComponentB wrapperB = new ConcreteComponentB(raw);
		wrapperB.operation();
		System.out.println();
		ConcreteComponentB wrapperBA = new ConcreteComponentB(wrapperA);
		wrapperBA.operation();
		System.out.println();
	}
总结:
Component:抽象的接口封装
ConcreteComponent:具体的实体类,即将被修饰的类
Decorator:装饰者实体父类,负责封装具体装饰者的方法,内部保留一个对实体类的引用
ConcreteComponentA:具体不同的装饰者

装饰者模式利用构造函数或者set函数通过把ConcreteComponent的具体类设置到不同的装饰类中进行层层装饰,达到最后所需的封装。这样有效的把类的核心功能和装饰的功能分别开,进而可以去除相关类中重复的装饰逻辑。

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值