atwood-pan

 

10-设计模式——装饰器模式

设计模式——装饰器模式

装饰器模式 ==> Decorator

开闭原则:类应该对扩展开放,对修改关闭:也就是添加新功能时不需要修改代码。(对修改关闭,对扩展开放)

模式定义:

在不改变原有对象的基础上,将功能附加到对象上

为对象动态添加功能


装饰者(Decorator)和具体组件(ConcreteComponent)都继承自组件(Component),具体组件的方法实现不需要依赖于其它对象,而装饰者组合了一个组件,这样它可以装饰其它装饰者或者具体组件。

所谓装饰,就是把这个装饰者套在被装饰者之上,从而动态扩展被装饰者的功能。

装饰者的方法有一部分是自己的,这属于它的功能,然后调用被装饰者的方法实现,从而也保留了被装饰者的功能。可以看到,具体组件应当是装饰层次的最低层,因为只有具体组件的方法实现不需要依赖于其它对象。

应用场景:

扩展一个类的功能或给一个类添加附加职责

优点:

  1. 不改变原有对象的情况下给一个对象扩展功能
  2. 使用不同的组合可以实现不同的效果
  3. 符合开闭原则(对修改关闭,对扩展开放)
package com.example.designpatterns.decorator;

/**
 * @program: DesignPatterns
 * @description: 装饰器模式
 * @author: Coder_Pan
 * @create: 2022-04-13 15:55
 **/
public class DecoratorTest {
    public static void main(String[] args) {
        System.out.println("装饰器模式......");
        System.out.println("_______________原始需求________________");
        //原始需求
        Component component = new ConcreteComponent();
        component.operation();
        System.out.println("_______________新增需求1________________");
        //新增需求1
        ConcreteDecorator concreteDecorator = new ConcreteDecorator(component);
        concreteDecorator.operation();
        System.out.println("_______________新增需求2________________");
        //新增需求2
        ConcreteDecorator1 concreteDecorator1 = new ConcreteDecorator1(concreteDecorator);
        concreteDecorator1.operation();
    }
}

interface Component {
    /**
     * operation
     */
    void operation();
}
class ConcreteComponent implements Component {

    @Override
    public void operation() {
        System.out.println("拍照");
    }
}

/**
 * 定义Decorator装饰器
 */
abstract class Decorator implements Component {
    /**
     * 使装饰器持有Component的引用
     */
    Component component;

    public Decorator(Component component) {
        this.component = component;
    }
}
/**
 * 添加滤镜效果
 */
class ConcreteDecorator extends Decorator {

    public ConcreteDecorator(Component component) {
        super(component);
    }

    @Override
    public void operation() {
        System.out.println("添加美颜......");
        //调用父级的方法
        component.operation();
    }
}
class ConcreteDecorator1 extends Decorator {

    public ConcreteDecorator1(Component component) {
        super(component);
    }

    @Override
    public void operation() {
        System.out.println("添加滤镜.....");
        component.operation();
    }
}

posted on 2022-04-13 16:11  JavaCoderPan  阅读(11)  评论(0编辑  收藏  举报  来源

导航