简述-装饰者模式

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/ddxxii/article/details/84108172

装饰模式

介绍

结构型模式之一,通过装饰者持有组件(被装饰者)的引用,也含有调用组件的方法。而这两个往往两个都是抽象,都有具体的实现。那么在具体的装饰者中,调用具体的组件方法,使用super方式来调用,再其调用前后可以自由添加想用的新增方法,这新增方法就是装饰了。

Android中咱们常用的startActivity()等方法,是在Context中,而具体实现是ContextImpl,然而持有ContextImpl的是Activity继承对象ContextWrapper。这也是装饰者模式的体现。

UML

  • Component : 抽象组件,被装饰者
  • ConcreteComponent : 具体组件
  • Decorator : 装饰者,其内部有一个指向被装饰者的引用,大多数情况该类抽象,如果逻辑单一,可以直接处理为具体装饰者。
  • ConcreteDecortorA、ConcreteDecortorB : 具体装饰者

使用场景

  • 需要透明且动态扩展该类的功能时

事例

比如我们一开始只有一个喝水的功能,在途中需要新增加一个吃鸡腿和吃鸡翅的功能,但是我们又不想去动到原本的喝水的功能业务,那么就可以采用装饰着模式来修改啦。

  1. 建立抽象组件:提供功能方法
/**
 * 装饰组件
 * 提供操作方法
 */
public interface Component {
    /**
     * 操作方法
     */
    void operation();
}
  1. 具体组件:实现抽象组件方法
/**
 * 具体组件
 * 喝水
 */
public class ConcreateComponent implements Component {
    @Override
    public void operation() {
        System.out.println("喝水");
    }
}
  1. 装饰者:实现抽象方法,并调用具体组件前后扩展功能
/**
 * 装饰者
 */
public class Decorator implements Component {
    /**
     * 持有要装饰的组件
     */
    private Component component;

    public Decorator(Component component) {
        this.component = component;
    }

    /**
     * 拥有与组件一样的方法,但是在前后和扩展功能
     */
    @Override
    public void operation() {
        System.out.println("吃鸡腿");
        component.operation();
        System.out.println("吃鸡翅");
    }
}
  1. 测试类:
public static void main(String[] strings) {

        System.out.println("一开始,直接操作功能组件");
        Component component = new ConcreateComponent();
        component.operation();


        System.out.println("扩展功能,通过装饰者调用");
        Component decorator = new Decorator(component);
        decorator.operation();
    }
  1. 输出:
一开始,直接操作功能组件
喝水
扩展功能,通过装饰者调用
吃鸡腿
喝水
吃鸡翅

当需要在流程上扩展功能的时候,就可以添加装饰者来扩展调用,这样就不用动到原有的组件业务了,达到了开关闭原则。

总结:装饰着模式,不动原有业务,在原有业务前后去扩展相关功能,达到开关比原则,在遇到这一类扩展情况的时候,想想可不可以用它来实现扩展,根据具体情况考虑使用即可

猜你喜欢

转载自blog.csdn.net/ddxxii/article/details/84108172