编程模式之装饰模式(Decorator)

装饰模式由四个角色组成:抽象组件角色,抽象装饰者角色,具体组件角色,具体装饰者角色

抽象组件角色:给出一个抽象接口,以规范“准备接受附加功能”的对象。

抽象装饰者角色:持有一个组件(Component)对象的引用,并定义一个与抽象组件接口一致的接口。

具体组件角色:定义一个准备接受附加功能的类。

抽象装饰者角色:负责给组件对象“贴上”附加的责任。

类图:

JAVA代码:

Conponent.java

package com.decorator;

public interface Component
{
    void doSomeThing();
}

ConcreteConponent.java

package com.decorator;

public class ConcreteComponent implements Component
{

    @Override
    public void doSomeThing()
    {
        System.out.println("功能A");
    }

}

Decorator.java

package com.decorator;

public class Decorator implements Component
{
    private Component component;    //待修饰对象的一个引用
    
    public Decorator(Component component)
    {
        this.component = component;
    }

    @Override
    public void doSomeThing()
    {
        this.component.doSomeThing();
    }

}

ConcreteDecorator1.java

package com.decorator;

public class ConcreteDecorator1 extends Decorator
{

    public ConcreteDecorator1(Component component)
    {
        super(component);
    }
    
    @Override
    public void doSomeThing()
    {
        super.doSomeThing();
        doAnotherThing();
    }

    private void doAnotherThing()
    {
        System.out.println("功能B");
    }
}

ConcreteDecorator2.java

package com.decorator;


public class ConcreteDecorator2 extends Decorator
{

    public ConcreteDecorator2(Component component)
    {
        super(component);
    }
    
    @Override
    public void doSomeThing()
    {
        super.doSomeThing();
        doAnotherThing();
    }
    
    private void doAnotherThing()
    {
        System.out.println("功能C");
    }
}

Test.java

package com.decorator;


public class Test
{
    public static void main(String[] args)
    {
        //ConcreteDecorator1对象装饰了ConcreteComponent对象
        //ConcreteDecorator2对象又修饰了ConcreteDecorator1对象
        //在不增加一个同时拥有ConcreteComponent、ConcreteDecorator1和ConcreteDecorator2三个类的功能
        //于一身的一个“新的类”的情况下,通过修饰,实现了同时拥有这些功能
        Component component = new ConcreteDecorator2(new ConcreteDecorator1(new ConcreteComponent()));
        
        component.doSomeThing();
    }
    
}

总结:

  装饰模式以对客户端透明的方式扩展对象的功能,是继承关系的一个替代方案,其可以在不创造更多子类的情况下将对象的功能加以扩展。

原文地址:https://www.cnblogs.com/justmehyp/p/6217754.html