您的位置:首页 > 其它

【设计模式】装饰模式

2017-03-30 22:27 295 查看
设计模式总结链接

装饰模式又名包装(Wrapper)模式。装饰模式以对客户端透明的方式扩展对象的功能,是继承关系的一个替代方案

一。简解

装饰模式从两方面理解,透明和扩展,主要是通过继承的方式用子类实现对父类功能的扩展。很好的实现了向下兼容的效果,开闭原则,不改变原类的情况下扩展。

二。用途

在系统升级是很常用,系统中很容易出现对此类的使用,如果直接扩展的话很容易出现问题。同时为了满足开闭原则,使用子类对其功能进行扩展,两全其美既保证了父类的不变动,又实现了对父类的扩展。

三。实例

文件读取:

public class IOTest {

public static void main(String[] args) throws IOException {
// 流式读取文件
DataInputStream dis = null;
try{
dis = new DataInputStream(
new BufferedInputStream(
new FileInputStream("test.txt")
)
);
//读取文件内容
byte[] bs = new byte[dis.available()];
dis.read(bs);
String content = new String(bs);
System.out.println(content);
}finally{
dis.close();
}
}

}


 观察上面的代码,会发现最里层是一个FileInputStream对象,然后把它传递给一个BufferedInputStream对象,经过BufferedInputStream处理,再把处理后的对象传递给了DataInputStream对象进行处理,这个过程其实就是装饰器的组装过程,FileInputStream对象相当于原始的被装饰的对象,而BufferedInputStream对象和DataInputStream对象则相当于装饰器。

装饰模式的类图如下:



在装饰模式中的角色有:

抽象构件(Component)角色:给出一个抽象接口,以规范准备接收附加责任的对象。

具体构件(ConcreteComponent)角色:定义一个将要接收附加责任的类。

装饰(Decorator)角色:持有一个构件(Component)对象的实例,并定义一个与抽象构件接口一致的接口。

具体装饰(ConcreteDecorator)角色:负责给构件对象“贴上”附加的责任。

抽象构件角色

public interface Component {

public void sampleOperation();

}


具体构件角色

public class ConcreteComponent implements Component {

@Override
public void sampleOperation() {
// 写相关的业务代码
}

}


装饰角色

public class Decorator implements Component{
private Component component;

public Decorator(Component component){
this.component = component;
}

@Override
public void sampleOperation() {
// 委派给构件
component.sampleOperation();
}

}


具体装饰角色

public class ConcreteDecoratorA extends Decorator {

public ConcreteDecoratorA(Component component) {
super(component);
}

@Override
public void sampleOperation() {
     super.sampleOperation();
// 写相关的业务代码
}
}


public class ConcreteDecoratorB extends Decorator {

public ConcreteDecoratorB(Component component) {
super(component);
}

@Override
public void sampleOperation() {
      super.sampleOperation();
// 写相关的业务代码
}
}


四。优点

在向下兼容上考虑的时分周到,两全其美,不仅扩展了功能,而且未改变原来的类(透明,扩展

五。不足

由于大量的使用了继承,在某些地方还是不太合适。某些类未引用过,可以直接删除或者覆盖,通过装饰的方式显得有点乱。父类出现问题会影响到所有的子类,这一点不太好(父类运行错误会导致很大问题,修改起来比较方便
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息