装饰模式

Posted by Lazy on July 13, 2016

##装饰模式

  • 就是给一个对象增加一些新的功能,并且装饰的对象的和被装饰的对象都要实现同一个接口,装饰者持有被装饰者的对象的实例。
public interface Sourceable {
	public void method();
}

被装饰的类

public class Source implements Sourceable {

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

装饰的类

public class Decorator implements Sourceable {

	private Sourceable source;
    将装饰类当构造传递进来
	public Decorator(Sourceable source){
		super();
		this.source = source;
	}
	@Override
	public void method() {
		System.out.println("before decorator!");
		source.method();
		System.out.println("after decorator!");
	}
}

测试代码

public class DecoratorTest {

	public static void main(String[] args) {
		Sourceable source = new Source();
		Sourceable obj = new Decorator(source);
		obj.method();
	}
}

装饰器模式的应用场景: 1、需要扩展一个类的功能。 2、动态的为一个对象增加功能,而且还能动态撤销。(继承不能做到这一点,继承的功能是静态的,不能动态增删。) 缺点:产生过多相似的对象,不易排错!