装饰模式也叫装饰者模式、包裹模式。
装饰模式可以动态的给对象添加一些功能,相比继承来说更加灵活。
特点:
- 装饰对象和真实对象有相同的接口。这样客户端对象就可以和真实对象相同的方式和装饰对象交互。
- 装饰对象包含一个真实对象的引用。
- 装饰对象接受所有来自客户端的请求。它把这些请求转发给真实的对象。
- 装饰对象可以在转发这些请求以前或以后增加一些附加功能。这样就确保了在运行时,不用修改给定对象的结构就可以在外部增加附加的功能。在面向对象的设计中,通常是通过继承来实现对给定类的功能扩展。
角色:
- 抽象构件角色:给出一个抽象接口,一规范准备接受附加责任的对象。
- 具体构件角色:定义一个将要接受附加责任的类。
- 装饰角色:持有一个构件对象的引用,并定义一个与抽象构建接口一致的接口。
- 具体装饰角色:负责给构件对象添加一些功能。
public class Test
{
public static void main(String[] args)
{
// 要完成的基本功能A
Component component = new ConcreteComponent();
// 添加额外的功能A
Decorator decorator1 = new ConcreteDecorator(component);
// 添加额外的功能B
Decorator decorator2 = new ConcreteDecorator2(decorator1);
decorator2.doSomething();
// -------------------------------------------------
System.out.println("\n--------------------\n");
// 要完成的基本功能B
component = new ConcreteComponent2();
// 添加额外的功能A
decorator1 = new ConcreteDecorator(component);
// 添加额外的功能B
decorator2 = new ConcreteDecorator2(decorator1);
decorator2.doSomething();
}
}
// 抽象构件角色
interface Component
{
void doSomething();
}
// 具体构建角色A
class ConcreteComponent implements Component
{
@Override
public void doSomething()
{
System.out.println("基本功能A");
}
}
// 具体构建角色B
class ConcreteComponent2 implements Component
{
@Override
public void doSomething()
{
System.out.println("基本功能B");
}
}
// 装饰角色
class Decorator implements Component
{
private Component component;
public Decorator(Component component)
{
this.component = component;
}
@Override
public void doSomething()
{
component.doSomething();
}
}
// 具体装饰角色A
class ConcreteDecorator extends Decorator
{
public ConcreteDecorator(Component component)
{
super(component);
}
@Override
public void doSomething()
{
super.doSomething();
doOtherthing();
}
private void doOtherthing()
{
System.out.println("添加的额外功能A");
}
}
// 具体装饰角色B
class ConcreteDecorator2 extends Decorator
{
public ConcreteDecorator2(Component component)
{
super(component);
}
@Override
public void doSomething()
{
super.doSomething();
doOtherthing();
}
private void doOtherthing()
{
System.out.println("添加的额外功能B");
}
}
输出
基本功能A
添加的额外功能A
添加的额外功能B
--------------------
基本功能B
添加的额外功能A
添加的额外功能B