设计模式之装饰器模式

装饰器模式

文章目录

定义

装饰模式(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

相关推荐
庞轩px14 小时前
HotSpot详解——符号引用、句柄池、直接指针的终极解密
java·jvm·设计模式·内存·虚拟机·引用·klass
Yu_Lijing16 小时前
基于C++的《Head First设计模式》笔记——责任链模式
c++·笔记·设计模式·责任链模式
青木川崎19 小时前
设计模式之面试题
java·开发语言·设计模式
Yu_Lijing2 天前
基于C++的《Head First设计模式》笔记——生成器模式
c++·笔记·设计模式
sg_knight2 天前
设计模式实战:策略模式(Strategy)
java·开发语言·python·设计模式·重构·架构·策略模式
吐个泡泡v2 天前
Python 开发“设计模式”指南
python·设计模式
程序员小寒2 天前
JavaScript设计模式(一):单例模式实现与应用
javascript·单例模式·设计模式
砍光二叉树2 天前
【设计模式】创建型-原型模式
设计模式·原型模式
helloworddm2 天前
第一篇:设计模式在 Android 视频播放器中的实战应用
android·设计模式·音视频