java设计模式----装饰器模式

Decorator装饰器,顾名思义,就是动态地给一个对象添加一些额外的职责,就好比为房子进行装修一样。因此,装饰器模式具有如下的特征:

它必须具有一个装饰的对象。

它必须拥有与被装饰对象相同的接口。

它可以给被装饰对象添加额外的功能。

用一句话总结就是:保持接口,增强性能。

装饰器通过包装一个装饰对象来扩展其功能,而又不改变其接口,这实际上是基于对象的适配器模式的一种变种。它与对象的适配器模式的异同点如下。

相同点:都拥有一个目标对象。

不同点:适配器模式需要实现另外一个接口,而装饰器模式必须实现该对象的接口。

先写一个接口类:Sourcable

package model;

public interface Sourcable {
	public void opration();

}

 

 再设置一个实现类:Source,重写方法。

package model;

public class Source implements Sourcable{
	public void opration(){
		System.out.println("原始类方法");
	}

}

 装饰器类 Decorator1.java 采用了典型的对象适配器模式,它首先拥有一个 Sourcable 对象 source ,该对象通过构造函 数进行初始化。然后它实现了 Sourcable.java 接口,以期保持与 source 同样的接口,并在重写的operation() 函数中调用  source  operation() 函数,在调用前后可以实现自己的输出,这就是装饰器所扩展的功能

 

package model;

public class Decorator1 implements Sourcable{
	private Sourcable sourcable;
	public Decorator1(Sourcable sourcable){
		super();
		this.sourcable=sourcable;
	}
	

	@Override
	public void opration() {
		System.out.println("第一个装饰器前");
		sourcable.opration();
		System.out.println("第一个装饰器后");
	}

}

 

再建两个输出不同提示的装饰器Decorato2.java ,Decorator3.java 

package model;

public class Decorator2 implements Sourcable{
	private Sourcable sourcable;
	public Decorator2(Sourcable sourcable){
		super();
		this.sourcable=sourcable;
	}
	

	@Override
	public void opration() {
		System.out.println("第二个装饰器前");
		sourcable.opration();
		System.out.println("第二个装饰器后");
	}

}
package model;

public class Decorator3 implements Sourcable{
	private Sourcable sourcable;
	public Decorator3(Sourcable sourcable){
		super();
		this.sourcable=sourcable;
	}
	

	@Override
	public void opration() {
		System.out.println("第三个装饰器前");
		sourcable.opration();
		System.out.println("第三个装饰器后");
	}

}

测试下:

package model;

public class DecoratorTest {
	public static void main(String[] args) {
		Sourcable source=new Source();
		//装饰类对象
		Sourcable sc=new Decorator1(new Decorator2(new Decorator3(source)));
		sc.opration();	
	}
}

 输出结果为:

第一个装饰器前
第二个装饰器前
第三个装饰器前
原始类方法
第三个装饰器后
第二个装饰器后
第一个装饰器后

 

 

原文地址:https://www.cnblogs.com/JAYIT/p/5000852.html