装饰模式(包装模式)

定义:在不改变对象结构的情况下,动态地给该对象增加一些职责(即额外功能)的模式。

一. 结构图

抽象构件:规范准备接收附加责任的对象。
具体构件:定义一个将要接收附加责任的类。

抽象装饰:持有一个构件(Component)对象的实例,并实现一个与抽象构件接口一致的接口。
具体装饰:负责给构件对象添加上附加的责任。

二 . 实现

package decorator;
public class DecoratorPattern
{
    public static void main(String[] args)
    {
        Component p=new ConcreteComponent();
        p.operation();
        System.out.println("---------------------------------");
        Component d=new ConcreteDecorator(p);
        d.operation();
    }
}
//抽象构件角色
interface  Component
{
    public void operation();
}
//具体构件角色
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)
    {
        this.component=component;
    }   
    public void operation()
    {
        component.operation();
    }
}
//具体装饰角色
class ConcreteDecorator extends Decorator
{
    public ConcreteDecorator(Component component)
    {
        super(component);
    }   
    public void operation()
    {
        super.operation();
        addedFunction();
    }
    public void addedFunction()
    {
        System.out.println("为具体构件角色增加额外的功能addedFunction()");           
    }
}

三. 应用场景

1. 需要给一个类添加职责,但不能通过派生子类实现。例如:该类被隐藏或该类是终极类或采用继承方式会产生大量的子类。[不允许派生]
2. 需要对现有一组基本功能,进行排列组合而产生非常多的功能时,采用继承关系很难实现,而采用装饰模式却很好实现。[排列组合]
3. 对象的功能被要求可以动态添加和撤销时。[动态新增和撤销]

四. 优缺点

优点: 扩展对象的功能比继承方式更加灵活。 可以设计出多个不同的具体装饰类,创造出多个不同行为的组合。
缺点:增加了许多子类会增添程序复杂性。

五. 实例

原文地址:https://www.cnblogs.com/shijianchuzhenzhi/p/13200586.html