每日设计模式之装饰模式

装饰模式

装饰模式(Decorator Pattern):动态地给一个对象增加一些额外的职责,就增加对象功能来说, 装饰模式比生成子类实现更为灵活。装饰模式是一种对象结构型模式

//抽象构件
public interface DPComponent {
    void operation();
}
//具体构件
public class DPConcreteComponent implements DPComponent {

    @Override
    public void operation() {
        System.out.println("我是具体组件逻辑");
    }
}
//抽象装饰类
public class DPDecorator implements DPComponent{
    private DPComponent dpComponent;

    public DPDecorator(DPComponent dpComponent) {
        this.dpComponent = dpComponent;
    }

    @Override
    public void operation() {
        dpComponent.operation();
    }
}
//具体装饰类
public class DPConcreteDecorator extends DPDecorator {

    public DPConcreteDecorator(DPComponent dpComponent) {
        super(dpComponent);
    }
    @Override
    public void operation() {
        super.operation();
        addedBehavior();
    }

    public void addedBehavior(){
        System.out.println("这个我新增的行为");
    }
}

public class DPClient {
    public static void main(String[] args) {
        DPConcreteDecorator decorator = new DPConcreteDecorator(new DPConcreteComponent());
        decorator.operation();
        System.out.println("=====================================================");
        DPConcreteDecorator decorator1 = new DPConcreteDecorator(decorator);
        decorator1.operation();
        System.out.println("=====================================================");
        DPConcreteDecorator decorator2 = new DPConcreteDecorator(decorator1);
        decorator2.operation();
    }
}

优点

  1. 对于扩展一个对象的功能,装饰模式比继承更加灵活性,不会导致类的个数急剧增加
  2.  可以通过一种动态的方式来扩展一个对象的功能,通过配置文件可以在运行时选择不同的 具体装饰类,从而实现不同的行为
  3.  可以对一个对象进行多次装饰,通过使用不同的具体装饰类以及这些装饰类的排列组合, 可以创造出很多不同行为的组合,得到功能更为强大的对象
  4. 具体构件类与具体装饰类可以独立变化,用户可以根据需要增加新的具体构件类和具体装 饰类,原有类库代码无须改变,符合“开闭原则”

缺点

  1. 使用装饰模式进行系统设计时将产生很多小对象,这些对象的区别在于它们之间相互连接 的方式有所不同,而不是它们的类或者属性值有所不同,大量小对象的产生势必会占用更多 的系统资源,在一定程序上影响程序的性能
  2. 装饰模式提供了一种比继承更加灵活机动的解决方案,但同时也意味着比继承更加易于出 错,排错也很困难,对于多次装饰的对象,调试时寻找错误可能需要逐级排查,较为繁琐

使用场景

  1.  在不影响其他对象的情况下,以动态、透明的方式给单个对象添加职责。
  2. 当不能采用继承的方式对系统进行扩展或者采用继承不利于系统扩展和维护时可以使用装 饰模式。
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值