【设计模式】装饰模式

来源:互联网 发布:剑三毒哥妖孽捏脸数据 编辑:程序博客网 时间:2024/05/21 00:20

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");     }}
0 0
原创粉丝点击