装饰者模式

简介

  • 装饰者模式是一种结构型设计模式,它允许你在运行时动态地将责任附加到对象上,而不会影响其他对象。该模式可以在不使用子类继承的情况下扩展对象的功能。

用途

  • 装饰者模式的主要用途是在不影响其他对象的情况下,动态地为对象添加新的行为。例如,在一个系统中有一个基本的对象,我们可以使用装饰者模式来为该对象添加新的功能或行为,这样可以保证对象的原有功能不受影响,同时也不需要修改基本对象的代码。

  • 另一个常见的用途是在复杂的继承结构中,使用装饰者模式来代替继承。继承在一定程度上增加了代码的复杂性,而且一旦继承结构变得太深,就很难进行维护和扩展。装饰者模式可以帮助我们避免这种问题,因为它允许我们在运行时动态地为对象添加新的行为,而不需要创建大量的子类。

应用场景

  • 动态地给对象添加新的行为,而不影响其他对象。
  • 避免使用大量的子类继承来扩展对象的功能。
  • 在不改变原有代码的情况下,为对象添加新的行为。
  • 用于构建具有复杂功能的对象。

代码

以下为动态给coffee添加属性的代码,通过给接口不添加装饰者实现更多的功能
public class Test {

    public static void main(String[] args) throws IOException, XMLParserException, InvalidConfigurationException, SQLException, InterruptedException {
        Coffee coffee = new SimpleCoffee();
        coffee = new Milk(coffee);
        coffee = new Sugar(coffee);
        System.out.println(coffee.getCost());
        System.out.println(coffee.getDescription());

    }

}
// 定义咖啡接口
interface Coffee {
    double getCost();
    String getDescription();
}

// 实现简单的咖啡类
class SimpleCoffee implements Coffee {
    @Override
    public double getCost() {
        return 1.0;
    }

    @Override
    public String getDescription() {
        return "Simple coffee";
    }
}

// 定义装饰者类
abstract class CoffeeDecorator implements Coffee {
    protected Coffee decoratedCoffee;

    public CoffeeDecorator(Coffee coffee) {
        this.decoratedCoffee = coffee;
    }

    public double getCost() {
        return decoratedCoffee.getCost();
    }

    public String getDescription() {
        return decoratedCoffee.getDescription();
    }
}

// 实现具体的装饰者类:牛奶
class Milk extends CoffeeDecorator {
    public Milk(Coffee coffee) {
        super(coffee);
    }

    public double getCost() {
        return super.getCost() + 0.5;
    }

    public String getDescription() {
        return super.getDescription() + ", milk";
    }
}

// 实现具体的装饰者类:糖
class Sugar extends CoffeeDecorator {
    public Sugar(Coffee coffee) {
        super(coffee);
    }

    public double getCost() {
        return super.getCost() + 0.2;
    }

    public String getDescription() {
        return super.getDescription() + ", sugar";
    }

}
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容