设计模式-装饰器模式(Decorator Pattern)

问题思考

有这样一个需求?我们有汽车这个对象提供了基本的行驶功能,分别有3种不能品牌的汽车继承了汽车接口,随着科技的发展,汽车衍生出了很多其他的功能,比如:自动驾驶在这种情况下,你会怎么实现代码呢?

  • 可以直接修改3个具体汽车类。
    (违背了开闭原则)

  • 新增3个子类,分别继承3个具体汽车类,在子类中实现自动驾驶。
    (想法不错,但是这样会不会增加过多了类了呢,后期可能还会新增飞行,潜水的功能,那子类不是会越来越庞大了)

对于类的扩展,不仅可以通过继承实现,还可以通过组合来实现

针对上述问题:我们不需要给每个汽车实现类都增加自动驾驶的子类,只需要定义一个自动驾驶的包装类,让汽车对象成为包装类的成员就好啦~后续如果增加飞行、潜水的功能,只需要在自动驾驶的包装类外再套一个飞行包装类、潜水包装类就能实现啦

4种角色

  • 抽象构件(Component):可以是接口或抽象类,是被装饰类的原始对象,定义了被装饰类的行为。

  • 具体构建(ConcreteComponent):实现或继承Component的一个具体对象,即被装饰类。

  • 抽象装饰角色(Decorator):一般是抽象类,实现了Component接口,在它的属性里有一个变量指向Component,这么做是为了实现多层嵌套包装。所有的包装类,都继承自Decorator。继承自Component接口,可以让每一个装饰器本身也可以被更外层的装饰器所包装,包装的方式就是把Component对象作为参数,传入到外层装饰器的构造函数当中。

  • 具体装饰角色(ConcreteDecorator):实现Decorator,并给ConcreteComponent增加新的功能。

代码实现

  • 汽车类(Component):
public interface Car {

    void run();
}
  • 具体汽车类(ConcreteComponent):
public class TeslaCar implements Car {
    @Override
    public void run() {
        System.out.println("特斯拉启动啦!");
    }
}
public class BmwCar implements Car{
    @Override
    public void run() {
        System.out.println("宝马开车啦!");
    }
}
  • 汽车装饰角色(Decorator):
public class CarDecorater implements Car{

    protected Car carDecorater;

    public CarDecorater(Car decoratedCar){
        this.carDecorater = decoratedCar;
    }

    @Override
    public void run() {

    }
}
  • 具体装饰角色(ConcreteDecorator):
public class AutoCarDecorator extends CarDecorator {

    public AutoCarDecorator(Car decoratedCar) {
        super(decoratedCar);
    }

    @Override
    public void run(){
        carDecorater.run();
        System.out.println("开启自动驾驶");
    }

}
public class FlyCarDecorator extends CarDecorator {

    public FlyCarDecorator(Car decoratedCar) {
        super(decoratedCar);
    }

    @Override
    public void run(){
        carDecorater.run();
        System.out.println("开启飞行模式");
    }

}
  • 测试类
public class Test {

    public static void main(String[] args) {

        TeslaCar teslaCar = new TeslaCar();
        BmwCar bmwCar = new BmwCar();
        CarDecorator autoBmwCar = new AutoCarDecorator(bmwCar);
        CarDecorator flyAutoTeslaCar = new FlyCarDecorator(new AutoCarDecorator(teslaCar));
        autoBmwCar.run();
        flyAutoTeslaCar.run();
    }
}


宝马开车啦!
开启自动驾驶
特斯拉启动啦!
开启自动驾驶
开启飞行模式

总结

装饰器模式:通过组合来实现类功能拓展,并且支持多层嵌套的设计模式。

  • 优点:是继承的有力补充,比继承更加灵活。装饰类和被装饰类可以分开独立发展。 符合"开闭原则"。
  • 缺点:虽然减少了类,但同时也需要新增类来表示继承关系种的对象。
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值