装饰模式又称为包装者模式,通过组成包装实现增加所要的功能。通过装饰模式可以在不创造更多子类的情况下将对象的功能加以扩展。
装饰模式的角色分配如下:
抽象构建角色(Component):给出一个抽象接口,以规范准备接收附加责任的对象。
具体构建角色(Concrete Component):定义一个即将要接收附加责任的类。
装饰角色(Decoretor):持有一个构建(Compent)对象的引用,并定义一个与抽象构建接口一致的接口。
具体装饰角色(Concrete Decorator):负责给构建对象“贴上”附加的责任。
**************************************************************************************************************
装饰模式与继承比较: 继承:
可以用来扩展特定对象的功能 用来扩展一类对象的功能
不需要子类 需要子类
动态 静态
运行时分配职责 编译时分派职责
*************************************************************************************************************
Component:
public interface Component
{
public void doSomething();
}
ConcreteComponent:
public class ConcreteComponent implements Component
{
public void doSomething()
{
System.out.println("功能A");
}
}
Decorator:
public class Decorator implements Component
{
private Component component;
public Decorator(Component component)
{
this.component = component;
}
public void doSomething()
{
component.doSomething();
}
}
ConcreteDecorator1:
public class ConcreteDecorator1 extends Decorator
{
public ConcreteDecorator1(Component component)
{
super(component);
}
public void doSomething()
{
super.doSomething();
this.doAnotherThing();
}
public void doAnotherThing()
{
System.out.println("功能B");
}
}
ConcreteDecorator2:
public class ConcreteDecorator2 extends Decorator
{
public ConcreteDecorator2(Component component)
{
super(component);
}
public void doSomething()
{
super.doSomething();
this.doAnotherThing();
}
public void doAnotherThing()
{
System.out.println("功能C");
}
}
这里定义了两个ConcreteDecorator,类似的根据功能还可以扩展
测试类,Client:
public class Client
{
public static void main(String[] args)
{
Component component = new ConcreteComponent();
component.doSomething();
System.out.println("------------------------");
Component component2 = new ConcreteDecorator1(component);
component2.doSomething();
System.out.println("------------------------");
Component component3 = new ConcreteDecorator2(component2);
component3.doSomething();
}
}
实验结果:
没经过一次decorator装饰,则会增加相应的功能
实际在IO中也会引用该模式,根据输入输出流的需要,进行一层层嵌套,实现相应的要求。