一、装饰者者模式简介:
装饰者模式:又名包装模式,以对客户端透明的方式扩展对象的功能,是继承关系的一个替代方案;装饰者模式以客户端透明的方式动态的给一个对象附加更多的责任。换而言之,客户端并不会觉得对象在装饰者前与装饰者后有什么不同。
装饰者模式可以在不创造更多子类的情况下,将对象的功能加以扩展。
装饰者模式把客户端的调用委派到被装饰者类。
装饰者模式的关键是在这种扩展完全是透明的。
装饰者模式是在不必改变原类文件和使用继承的情况下,动态的扩展一个对象的功能。它是通过创建一个包装对象,也就是装饰者来包裹真实的对象。
二、装饰者模式的角色:
抽象构件角色(Component):给出一个抽象类或者接口,定义出某些行为。
具体构件角色(Concrete Component):定义一个具体的对象,也就是 被装饰者对象 实现或者继承抽象构件角色。
装饰者角色(Decorator):持有构件对象(被装饰者)的引用, 实现或者继承抽象构件角色。
具体装饰者角色(Concrete Decorator):负责给对象加上附加的责任,也就是添加附加的功能。
三、装饰者模式VS继承:
装饰者模式:
1、用来扩展特定对象的功能
2、不需要创建子类
3、它是动态的
4、它在运行时分配职责
5、防止由于子类而导致的复杂和混乱
6、更多的灵活性
7、对于一个对象,同时可能有不同的装饰者对象
继承:
1、用来扩展一类对象的功能
2、需要创建子类
3、它是静态的
4、它在编译时分配职责
5、导致产生很多的子类
6、缺乏灵活性
四、装饰者模式的实现
下面举个例子来演示装饰者模式的实现,具体代码如下:
package com.guigu.decorator;
/**
* 抽象构件角色 类似于我们io中的 outPutStream
* @author Administrator
*/
public interface Component {
void doSomeThing();
}
package com.guigu.decorator;
/**
* 具体的构件角色 被装饰者的对象 由该类创建 类似于FileOutPutStream
* @author Administrator
*
*/
public class ConcreteComponent implements Component{
@Override
public void doSomeThing() {
System.out.println("功能A");
}
}
package com.guigu.decorator;
/**
* 装饰者角色 类似于FilterOutputStream
* @author Administrator
*
*/
public class Decorator implements Component{
private Component component ;
public Decorator( Component component) {
this.component = component;
}
@Override
public void doSomeThing() {
component.doSomeThing();
}
}
package com.guigu.decorator;
/**
* 具体的装饰者角色 类似于DataOutPutStream
* @author Administrator
*
*/
public class ConcreteDecorator extends Decorator{
public ConcreteDecorator(Component component) {
super(component);
}
@Override
public void doSomeThing() {
super.doSomeThing();
doAnotherSomeThing();
}
private void doAnotherSomeThing(){
System.out.println("功能B");
}
}
//测试类
package com.guigu.decorator;
import java.io.DataOutputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
public class Test {
public static void main(String[] args) throws FileNotFoundException{
//DataOutputStream dataOut = new DataOutputStream(new FileOutputStream("D:\\A.txt"));
Component component = new ConcreteComponent();
ConcreteDecorator decorator = new ConcreteDecorator(component);
decorator.doSomeThing();
}
}
//运行结果如下:
功能A
功能B