《设计模式》之十二:装饰模式

Decorator Pattern 装饰器模式是一种比较常见的模式,其定义如下:Attach additional responsibility to an object dynamically keeping the same interface. Decorators provide a flexible alternative to subclassing for extending functionality.

 

通用模板代码:

先定义最基本的需要修饰的Component抽象类

public abstract class Component {
    // 抽象方法
    public abstract void operate();
}

 实现类:

public class ConcreteComponent extends Component {
    @Override
    public void operate() {
        System.out.println("do something...");
    }
}

 抽象的装饰者:

public abstract class Decorator extends Component {
    private Component component = null;
    // 通过构造函数传递被修饰者
    public Decorator(Component _component) {
        this.component = _component;
    }

    // 委托给被修饰者执行
    @Override
    public void operate() {
        this.component.operate();
    }
}

 两个实现类:

public class ConcreteDecorator1 extends Decorator {
    public ConcreteDecorator1(Component _component) {
        super(_component);
    }

    private void method1() {
        System.out.println("method1 修饰");
    }

    // 重写父类的operate方法
    @Override
    public void operate() {
        this.method1();
        super.operate();
    }
}

 

public class ConcreteDecorator2 extends Decorator {
    public ConcreteDecorator2(Component _component) {
        super(_component);
    }

    private void method2() {
        System.out.println("method2 修饰");
    }

    // 重写父类的operate方法
    @Override
    public void operate() {
        super.operate();
        this.method2();
    }
}

 最后是应用场景:

public class Client {
    public static void main(String[] args) {
        Component component = new ConcreteComponent();
        // 第一次修饰
        component = new ConcreteDecorator1(component);
        // 第二次修饰
        component = new ConcreteDecorator2(component);
        //修饰后运行
        component.operate();
    }
}

 

装饰模式优点:

1,装饰类和被装饰类可以独立发展,而不会耦合。Component类无需知道Decorator类,而Decorator类也不用知道具体的构件

2,装饰模式是继承关系的一个替代方案。我们看装饰类Decorator,不管装饰多少层,返回对象还是Component,实现的还是is-a的关系。

3,装饰模式可以动态扩展一个实现类的功能,这不需要多说。

 

装饰模式缺点:

多层的装饰是比较复杂的

 

装饰模式的使用场景:

1,需要扩展一个类的功能,或给一个类增加附加功能

2,需要动态给一个对象增加功能,这些功能可以再动态撤销

3,需要为一批兄弟类进行改装或加装功能,当然首选装饰模式

 

本人博客已搬家,新地址为:http://yidao620c.github.io/

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值