设计模式之装饰器模式

装饰器模式

文章目录

定义

装饰模式(Decorator Pattern)是一种比较常见的模式,其定义如下:

Attach additional responsibilities to an object dynamically keeping the same interface.Decorators provide a flexible alternative to subclassing for extending functionality.(动态地给一个对象添加一些额外的职责。就增加功能来说,装饰模式相比生成子类更为灵活。)

优缺点

优点
  1. 装饰类和被装饰类可以独立发展,而不会相互耦合
  2. 装饰模式是继承关系的一个替代方案
  3. 装饰模式可以动态地扩展一个实现类的功能,这不需要多说,装饰模式的定义就是如此
缺点
  1. 需要扩展一个类的功能,或给一个类增加附加功能
  2. 需要动态地给一个对象增加功能,这些功能可以再动态地撤销
  3. 需要为一批的兄弟类进行改装或加装功能,当然是首选装饰模式

示例代码

  1. 定义接口或者抽象类

    java 复制代码
    public interface Component {
        void operate();
    }
  2. 抽象类实现上述接口

    java 复制代码
    public abstract class Decorator implements Component {
        private Component component;
    
        // 通过构造函数传递被修饰者
        public Decorator(Component component) {
            this.component = component;
        }
    
        @Override
        public void operate() {
            this.component.operate();
        }
    }
  3. 实现类

    java 复制代码
    public class ConcreteComponent implements Component {
        @Override
        public void operate() {
            System.out.println("do something");
        }
    }
  4. 具体实现类

    java 复制代码
    public class ConcreteDecorator1 extends Decorator {
        public ConcreteDecorator1(Component component) {
            super(component);
        }
    
        public void method1() {
            System.out.println("method1修饰");
        }
    
        // 重写父类operate方法
        @Override
        public void operate() {
            this.method1();
            super.operate();
        }
    }
    java 复制代码
    public class ConcreteDecorator2 extends Decorator {
        public ConcreteDecorator2(Component component) {
            super(component);
        }
    
        private void method2() {
            System.out.println("method2修饰");
        }
    
        @Override
        public void operate() {
            this.method2();
            super.operate();
        }
    }
  5. 测试方法

    java 复制代码
    @Test
    public void test() {
        Component component = new ConcreteComponent();
        // 第一次修饰
        component = new ConcreteDecorator1(component);
        // 第二次修饰
        component = new ConcreteDecorator2(component);
        // 修饰后运行
        component.operate();
    }

    运行结果如下:

    复制代码
    method2修饰
    method1修饰
    do something

    示例代码地址

    https://gitee.com/youxiaxiaomage/java-practices/tree/master/yxxmg-gof-sample/src/main/java/com/yxxmg/gof/structure/decorator

相关推荐
李广坤7 小时前
状态模式(State Pattern)
设计模式
李广坤8 小时前
观察者模式(Observer Pattern)
设计模式
李广坤9 小时前
中介者模式(Mediator Pattern)
设计模式
李广坤9 小时前
迭代器模式(Iterator Pattern)
设计模式
李广坤10 小时前
解释器模式(Interpreter Pattern)
设计模式
阿无,13 小时前
java23种设计模式之前言
设计模式
Asort13 小时前
JavaScript设计模式(八):组合模式(Composite)——构建灵活可扩展的树形对象结构
前端·javascript·设计模式
数据智能老司机14 小时前
数据工程设计模式——数据基础
大数据·设计模式·架构
笨手笨脚の16 小时前
设计模式-代理模式
设计模式·代理模式·aop·动态代理·结构型设计模式
Overboom1 天前
[C++] --- 常用设计模式
开发语言·c++·设计模式