设计模式——装饰器模式(附java源码案例)

装饰器模式,其实又叫做包装模式,其主要作用就是将附加的功能添加到别的类当中,让这个类实现其包含的类的方法,在具体的调用时,就会按照包装顺序进行调用。

Compoent

   提供一个统一接口,是装饰类和被装饰类的基础类

ConcreteComponent

  具体的实现类,对于接口当中的方式进行实现

Decorator

    继承了Componet接口,同时包含了一个Component接口对象,对于Component当中抽象方法的实现,调用的是,具体传递进来的componet方法,Decorator本身通过采用默认实现,他的存在仅仅是一个声明,只是为了生产出来一些用于装饰的子类,其子类才是具有装饰效果的类。

ConcreteDecoratorA

  具体的装饰类,继承自Decorator,实现了decorator当中的方法,同时提供了自己的一些方法。

public interface Component {
    void  doSomeThing();
}
public class ConcreteComponent implements Component {
    @Override
    public void doSomeThing() {
        System.out.println("功能A");
    }
}

主要是对于装饰类Decorator,不做任何多余的方法处理,只是调用传递进来接口的方法

public class Decorator implements Component {

    private Component component;

    public  Decorator(Component component){
        this.component = component;
    }
    @Override
    public void doSomeThing() {
        component.doSomeThing();
    }
}

具体的装饰类实现

public class ConcreteDecorator extends Decorator {

    public ConcreteDecorator(Component component) {
        super(component);
    }
    @Override
    public void doSomeThing(){
        super.doSomeThing();
        this.doAnthorThing();
    }
    public void doAnthorThing(){
        System.out.println("功能B!");
    }
}

装饰类二

public class ConcreteDecorator1 extends Decorator {
    public ConcreteDecorator1(Component component) {
        super(component);
    }
    @Override
    public void doSomeThing() {
        super.doSomeThing();
        this.doAnthorThing();
    }
    public void doAnthorThing() {
        System.out.println("功能C");
    }
}

接下来我们来看下测试代码

public class Client {
    public static void main(String[] args)throws Exception {
        Component component = new ConcreteComponent();
        component.doSomeThing();
        System.out.println("------------------");
        Component component1 = new ConcreteDecorator(new ConcreteComponent());
        component1.doSomeThing();
        System.out.println("------------------");
        Component component2 = new ConcreteDecorator1(new ConcreteDecorator(new ConcreteComponent()));
        component2.doSomeThing();
    }
}

执行结果

功能A
------------------
功能A
功能B!
------------------
功能A
功能B!
功能C

上述就是装饰器模式的一个大概实现我们对照来看下java IO包当中的实现

扫描二维码关注公众号,回复: 2475064 查看本文章

InputStream就是我们所说的Component角色对象,FileInputStream就是对应的一个ConcreteComponent角色,FilterInputStream就是我们所说的Decorator角色,继承了Component角色,同时持有了一个Component对象,FilterInputStream也正如我们所介绍的,其方法当中的实现,基本上都是调用传入进来的Component接口的实现,它本身并不做装饰性操作,主要是让其子类去实现装饰性的工作。而BufferedInputStream就是ConcreteDecorator角色,其中也是持有了Component对象的。

下面这篇文章具体讲述了为什么要使用装饰器模式,以及在自己的项目当中如何使用装饰器模式

装饰器模式(Decorator)——深入理解与实战应用

猜你喜欢

转载自blog.csdn.net/summerzbh123/article/details/81262078
今日推荐