装饰器模式-java实现

装饰器模式

介绍

装饰器模式也被称为包装模式,是指在不改变原有对象的基础上,不直接依赖继承关系,提供比继承更有弹性的替代方案,从而达到扩展对象的功能,装饰器的核心是功能扩展

角色构成

Component:原有功能的接口

MyComponet:原有功能的实现

Decorator:抽象装饰器

XxxDecoratorImpl:具体装饰器的实现
在这里插入图片描述

实践

  1. 现在有一个其他人写的功能类

    public class MyComponent {
        public void operation(){
            System.out.println("operation...");
        }
    }
    
  2. 该类的功能已经不满足要求,现在需要对其扩展功能,但该类已被大量使用,不敢贸然改动。

    • 提取接口

      public interface Component {
          void operation();
      }
      
    • 实现继承关系

      public class MyComponent implements Component {
          @Override
          public void operation(){
              System.out.println("operation....");
          }
      }
      
  3. 构建装饰器抽象类,继承接口,构造函数的依赖注入

    public abstract class Decorator implements Component {
        public Component component;
    
        public Decorator(Component component) {
            this.component = component;
        }
    }
    
  4. 实现装饰器抽象类

    public class XxxDecoratorImpl extends Decorator{
        public XxxDecoratorImpl(Component component) {
            super(component);
        }
    
        @Override
        public void operation() {
            //前置动作
            before();
            component.operation();
            //后置动作
            after();
        }
        public void before(){
            System.out.println("前置操作....");
        }
    
        public void after(){
            System.out.println("后置操作....");
        }
    }
    
  5. 查看效果

    public class Test {
        public static void main(String[] args) {
            MyComponent myComponent = new MyComponent();
            XxxDecoratorImpl xxxDecorator = new XxxDecoratorImpl(myComponent);
            xxxDecorator.operation();
        }
    }
    

    在这里插入图片描述

在不修改原有类的基础上通过创建不同的装饰类,可以实现不同的功能。

  • 18
    点赞
  • 18
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值