zoukankan      html  css  js  c++  java
  • 一天学习一个设计模式之装饰模式

    装饰模式(Decorator),动态地给一个对象添加一些额外的职责,就增加功能来说,装饰模式比生成子类更为灵活。

          Component是定义一个对象接口,可以给这些对象动态地添加职责。ConcreteComponent是定义了一个具体的对象,也可以给这个对象添加一些职责。ConcreteComponent是定义了一个具体的对象,也可以给这个对象添加一些职责。Decorator,装饰抽象类,继承了Component,从外类来扩展Component类的功能,但对于Component来说,是无需知道Decorator的存在的。至于ConcreteDecorator就是具体的装饰对象,起到给Component添加职责的功能

    1 /**
    2  * 抽象构件角色
    3  */
    4 public interface IComponent {
    5     void sampleOperation();
    6 }
     1 /**
     2  * 具体构件角色
     3  */
     4 public class ConcreteComponent implements IComponent {
     5     @Override
     6     public void sampleOperation() {
     7         //写相关的业务代码
     8         System.out.println("具体对象的操作");
     9     }
    10 }
     1 /**
     2  * 装饰角色
     3  */
     4 public class Decorator implements IComponent {
     5     private IComponent component;
     6 
     7     public Decorator(IComponent component) {
     8         this.component = component;
     9     }
    10 
    11     @Override
    12     public void sampleOperation() {
    13         //委派给构件
    14         if (component!=null) {
    15             component.sampleOperation();
    16         }
    17     }
    18 }
     1 public class ConcreteDecoratorA extends Decorator  {
     2 
     3     public ConcreteDecoratorA(IComponent component) {
     4         super(component);
     5     }
     6 
     7     @Override
     8     public void sampleOperation() {
     9         super.sampleOperation();
    10         System.out.println("具体装饰对象A的操作");
    11     }
    12 }
     1 public class ConcreteDecoratorB extends Decorator {
     2 
     3     public ConcreteDecoratorB(IComponent component) {
     4         super(component);
     5     }
     6 
     7     @Override
     8     public void sampleOperation() {
     9         super.sampleOperation();
    10         System.out.println("具体装饰对象B的操作");
    11     }
    12 }
    1     public static void main(String[] args) {
    2         IComponent c=new ConcreteComponent();
    3         ConcreteDecoratorA d1=new ConcreteDecoratorA(c);
    4         ConcreteDecoratorB d2=new ConcreteDecoratorB(d1);
    5         c.sampleOperation();
    6         d1.sampleOperation();
    7         d2.sampleOperation();
    8     }

     在此代码中,装饰模式是利用构造参数(或专门写方法)来对对象进行包装。这样每个装饰对象的实现就和如何使用这个对象分离开了,每个装饰对象只关心自己的功能,不需要关心如何被添加到对象链当中。

     

  • 相关阅读:
    Dev中出现Error 0: 操作成功完成。
    找出一个二维数组中的鞍点,即该位置上的元素在该行上最大、在该列上最小。也可能没有没有鞍点。
    oracle 日常删除多余数据
    java程序练习:输入数字转换成中文输出(金额相关)
    linux压缩和解压文件命令
    一篇文章搞定Git——Git代码管理及使用规范
    读书心得(1)-20191108
    回表查询的说明
    Java 8新特性解读
    java-try catch中return在finally之前 还是之后执行
  • 原文地址:https://www.cnblogs.com/gousheng107/p/8037954.html
Copyright © 2011-2022 走看看