【Java设计模式】- 装饰器模式

概述

    装饰器模式:可以动态的为运行时的类添加行为。相比继承而言,继承是直接对某个类的行为进行扩展而装饰器模式是对某个对象进行扩展。
    原理:增加一个修饰类去实现被修饰类相同的接口,同时接收一个被修饰类的实例,并在修饰类中用自己的方法去包裹被修饰类的方法。

    经常使用的Collections的synchronizedList(List<T> list)等方法就是使用了装饰器模式。

简单实现

说明:
  • Conponent接口:被修饰类的接口。
  • ConcreateConponent:被修饰类的具体实现。
  • Decorator:装饰器实现。

Conponent:
只有一个方法
public interface Conponent {
	
	void conponentMethod();
	
}
ConcreateConponent:
具体实现
public class ConcreateConponent implements Conponent {

	@Override
	public void conponentMethod() {
		System.out.println("the original conponent method run");
	}

}

Decorator:
实现了Conponent接口从而拥有了和Conponent的实例一样的行为
接收一个Conponent的实例并用新的方法去包裹原来的方法。
这里的实现在conponentMethod执行之前和之后做了一个控制台输出,同时将该方法用一个互斥锁同步,使得conponentMethod方法线程安全。
public class Decorator implements Conponent {

	private Conponent source;
	
	private Object mutex = new Object();
	
	public Decorator(Conponent source) {
		this.source = source;
	}
	
	@Override
	public void conponentMethod() {
		synchronized (mutex) {
			System.out.println("do something before method run");
			source.conponentMethod();
			System.out.println("do something after method run");
		}
	}

}
测试:
public class Test {
	public static void main(String[] args) {
		Conponent source = new ConcreateConponent();
		Decorator decorator = new Decorator(source);
		decorator.conponentMethod();
	}
}
输出:
do something before method run
the original conponent method run
do something after method run

相比之下因为是使用的类的实例也就是对象,相比继承来说更加的灵活。同时不用新增更多的类定义。


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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值