装饰模式:动态的给一个对象添加一些额外的职责,就增加功能来说,装饰模式比生成子类更为灵活。它属于对象结构型模式。
装饰模式有四个角色:
- 抽象构件(Component)角色:定义一个抽象接口以规范准备接收附加责任的对象。
- 具体构件(Concrete Component)角色:实现抽象构件,通过装饰角色为其添加职责。
- 抽象装饰(Decorate)角色:继承抽象构件,并包含具体构件的实例,可以通过其子类扩展具体构件的功能。
- 具体装饰(Decorate)角色:实现抽象装饰的相关方法,并给具体构件对象添加附加的职责。
代码实现:
//Component类
interface Component
{
public void operation();
}
//ConcreteComponent类
class ConcreteComponent implements Component
{
public ConcreteComponent()
{
System.out.println("创建具体构件角色");
}
public void operation()
{
System.out.println("调用具体构件角色的方法operation()");
}
}
//抽象装饰角色
class Decorator implements Component
{
private Component component;
public Decorator(Component component)
{
//设置Component
this.component=component;
}
//重写Operation方法,实际执行的是Component的Operation方法
public void operation()
{
component.operation();
}
}
//具体装饰角色
class ConcreteDecorator extends Decorator
{
public ConcreteDecorator(Component component)
{
super(component);
}
public void operation()
{
//运行原Component的Operation方法,再执行本类的额外功能,相当于对原Component进行了装饰
super.operation();
addedFunction();
}
public void addedFunction()
{
System.out.println("为具体构件角色增加额外的功能addedFunction()");
}
}
//客户端代码
public static void main(String[] args) {
// TODO Auto-generated method stub
ConcreteComponent c = new ConcreteComponent();
//用a包装c
Decorate a = new ConcreteDecoratorA(c);
//再用b包装a
Decorate b = new ConcreteDecoratorB(a);
b.operation();
}
总结
装饰模式是为已有功能动态地添加更多功能的一种方式,它把每个要装饰的功能放在单独的类中,并让这个类包装它所要装饰的对象,因此,当需要执行特殊行为时,客户代码就可以在运行时根据需要有选择地包装对象。
装饰模式的优点:
- 采用装饰模式扩展对象的功能比采用继承方式更加灵活。
- 把类中的装饰功能从类中搬移去除,这样可以简化原有的类。
- 可以设计出多个不同的具体装饰类,创造出多个不同行为的组合。
缺点:增加了许多子类,如果过度使用会使程序变得很复杂。