Java设计模式之装饰器模式简单介绍
程序员文章站
2024-03-07 18:30:51
...
版权声明:本文是Kervin2的原创文章,欢迎批评指教。QQ:1991861807
本菜也是正在处于学习阶段,对于遗漏与讲错的知识点欢迎批评指教,qq1991861807
在介绍这个模式之前有句话我分享给大家:“利用继承设计子类的行为,是在编译时决定的,而且所有的子类都会继承到相同的行为。然而,如果能够利用组合的做法扩展对象的行为,就可以在运行时动态拓展”
适用场景:当我们想让类容易扩展,在不修改现有代码的情况下,就可搭配新的行为,可以接受新的功能来应对改变的需求。
类图(没用过几次visio,画的贼丑):
从这个类图中我们可以看到:装饰者和被装饰者必须是一样的类型,也就是有共同的超类,这是相当关键的地方。在这里,我们利用继承达到“类型匹配”,而不是利用继承获得行为。
基类:
public abstract class Beverage {
String description = "无饮料";
public String getDescription() {
return description;
}
public abstract double cost();
}
装饰者抽象类:
public abstract class CondimentDecorator extends Beverage{
public abstract String getDescription();
}
被装饰者类:
public class Espressp extends Beverage {
public Espressp() {
description = "浓缩咖啡";
}
@Override
public double cost() {
// 最后,我们计算浓缩咖啡的价格,现在不需要计算调料的价格,直接把浓缩咖啡的价格返回即可
return 1.99;
}
}
public class HouseBlend extends Beverage {
public HouseBlend() {
description = "深培咖啡";
}
@Override
public double cost() {
// 最后,我们计算浓缩咖啡的价格,现在不需要计算调料的价格,直接把浓缩咖啡的价格返回即可
return 0.89;
}
}
装饰者实现类:
//摩卡是一个装饰者,所以让他扩展自CondimentDecorator
public class Mocha extends CondimentDecorator {
Beverage beverage;
public Mocha(Beverage beverage) {
this.beverage = beverage;
}
@Override
public String getDescription() {
// TODO Auto-generated method stub
return beverage.getDescription() + ":搭配摩卡,";
}
@Override
public double cost() {
// TODO Auto-generated method stub
return 0.20 + beverage.cost();
}
}
//摩卡是一个装饰者,所以让他扩展自CondimentDecorator
public class Whip extends CondimentDecorator {
Beverage beverage;
public Whip(Beverage beverage) {
this.beverage = beverage;
}
@Override
public String getDescription() {
// TODO Auto-generated method stub
return beverage.getDescription() + ":搭配豆浆,";
}
@Override
public double cost() {
// TODO Auto-generated method stub
return 0.75 + beverage.cost();
}
}
//摩卡是一个装饰者,所以让他扩展自CondimentDecorator
public class Soy extends CondimentDecorator {
Beverage beverage;
public Soy(Beverage beverage) {
this.beverage = beverage;
}
@Override
public String getDescription() {
// TODO Auto-generated method stub
return beverage.getDescription() + ":搭配奶泡,";
}
@Override
public double cost() {
// TODO Auto-generated method stub
return 0.55 + beverage.cost();
}
}
测试类:
public class CoffeeTest {
public static void main(String[] args) {
Beverage beverage = new HouseBlend();
beverage = new Mocha(beverage);
beverage = new Mocha(beverage);
beverage = new Soy(beverage);
System.out.println(beverage.getDescription()+":"+beverage.cost());
}
}
输出: