Java设计模式:装饰模式

版权声明:本文为Zhang Phil原创文章,请不要转载! https://blog.csdn.net/zhangphil/article/details/88717828

假设Source类是需要被装饰的类,Decorator类是一个提供装饰功能的类,Decorator动态为Source添加功能。


public interface Sourceable {
	void method();
}

public class Source implements Sourceable{
	@Override
	public void method() {
		System.out.println("Source method");
	}
}
public class Decorator implements Sourceable {
	private Sourceable source;

	public Decorator(Sourceable source) {
		this.source = source;
	}

	@Override
	public void method() {
		System.out.println("装饰前");
		source.method();
		System.out.println("装饰后");
	}
}
public class Test {
	public static void main(String[] args) {
		try {
			Test test = new Test();
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	public Test() {
		Sourceable source = new Source();  
        Sourceable obj = new Decorator(source);  
        obj.method();  
	}
}

输出:

装饰前
Source method
装饰后

Source里面的method方法功能得到修饰和增强。

猜你喜欢

转载自blog.csdn.net/zhangphil/article/details/88717828