装饰模式

装饰模式

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

1. UML类图

2. 定义

  • Component抽象构件:是一个接口或者是抽象类,最核心的对象,最原始的对象
  • ConcreteComponent具体构件:ConcreteComponent是最核心、最原始、最基本的接口或抽象类的实现,你要装饰的就是它
  • Decorator装饰角色:一般是个抽象类,实现接口或者抽象方法,不一定有抽象方法,在它的属性里必然有一个private变量指向Component抽象构件
  • 具体装饰角色:ConcreteDecoratorA和ConcreteDecoratorB是两个具体的装饰类,把最核心最原始最基本的东西装饰成其他东西

3. 通用源码

//抽象构件
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 修饰");
    }
    //重写父类的Operation方法
    public void operate(){
        this.method1();
        super.operate();
    }
}

public class ConcreteDecorator2 extends Decorator{
    //定义被修饰者
    public ConcreteDecorator2(Component _component){
        super(_component);
    }
    //定义自己的修饰方法
    private void method2(){
        System.out.println("method1 修饰");
    }
    //重写父类的Operation方法
    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();
    }
}

4. 应用

4.1 优点

  1. 装饰类和被装饰类独立发展,不会相互耦合,即Component类无须知道Decorator类,Decorator类是从外部扩展Component类的功能,而Decorator也不用知道具体的构件
  2. 装饰模式是继承关系的一个替代方案。
  3. 可以动态地扩展一个实现类的功能。

4.2 缺点

多层的装饰是比较复杂的

4.3 使用场景

  • 需要扩展一个类的功能,或者给一个类增加附加功能
  • 需要动态地给一个对象增加功能,这些功能可以再动态地撤销
  • 需要为一批的兄弟类进行改装或加装功能,当然是首选装饰模式
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值