【设计模式】装饰模式

1. 定义:

表示动态的给一个对象添加一些新的功能,但是比生成子类方式更灵活。(当然利用子类继承父类也可以实现,但是不推荐)

核心:动态地扩展一个实现类的功能。(装饰模式是继承关系的一个替换方案,不管装饰多少层,返回的对象构件角色)

2. 角色:

  • 抽象构件(Component)角色:定义一个对象接口,可以给这些对象动态添加职责。
  • 具体构件(ConcreteComponent)角色:是定义了一个具体的对象(例如:车),也可以给这个对象添加一些其他职责。
  • 装饰(Decorator)角色:装饰抽象类,继承了Component,从外类来扩展Component类的功能,但对Component来说,是无需知道Decorator存在的。
  • 具体装饰(ConcreteDecorator)角色:就是具体的装饰对象了(飞车,水车..),它起到了给Component添加职责的功能。

这里写图片描述

以Java IO流中的设计为例:

  • 抽象构件角色——Input/OutputStream
  • 具体构件角色——FileInput/OutputStream
  • 装饰构件角色——FilterInput/OutputStream
  • 具体装饰角色——BufferedInput/OutputStream,DataInput/OutputStream

接口Component,定义了基本职责

package DecoratorPattem;

/**
 * InputStream
 * @author Administrator
 *
 */
public interface Component {
     public void doThingA();
}

类ConcreteComponent,实现了Component中的功能

package DecoratorPattem;

public class ConcreteComponent implements Component{

     /**
      * FileInputStream
      * @param args
      */
     @Override
     public void doThingA(){
          System.out.println("Do A thing");
     }
}

类Decorator,是ConcreteComponent的具体实现类

package DecoratorPattem;

/**
 * FilterInputStream
 * @author Administrator
 *
 */
public class Decorator implements Component {
     private Component component=null;

     public Decorator(Component component){
          this.component=component;
     }

     @Override
     public void doThingA() {
          component.doThingA();//调用被装饰对象的方法

     }
}

类ConcreteDecorator,对类Decorator做功能上的装饰。

package DecoratorPattem;


/*
 * BufferedInputStream
 */
public class ConcreteDecorator1 extends Decorator {

     public ConcreteDecorator1(Component component) {
          super(component);
     }
     @Override
     public void doThingA() {
          super.doThingA();//调用被包装类的方法
          doThingB();
     }

     //扩展功能
     private void doThingB(){
          System.out.println("Do B thing");
     }
}
package DecoratorPattem;

public class ConcreteDecorator2 extends Decorator {

     public ConcreteDecorator2(Component component) {
          super(component);
     }
     @Override
     public void doThingA() {
          super.doThingA();//调用被包装类的方法
          doThingC();
     }

     //扩展功能
     private void doThingC(){
          System.out.println("Do C thing");
     }
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值