最近在找工作,期间碰见了一道很有意思的面试题目:用装饰者设计模式,设计生产饮料的生产方式,之前自己的确了解过,但是设计的时候,还是碰见了一些问题,在此作为一个记录,如果以后有使用的机会的话,就拿起来使用
题目大概是设计生产出饮料的代码,利用装饰者模式:
首先抽象出一个类 Beverage 定义如下(被装饰对象):
package com.gavin.model;
public abstract class Beverage {
public abstract String getDescription();
public abstract double getCost();
}
这个商店暂时假定只生产两种饮料,代码定义如下(真正被装饰对象):
package com.gavin.model;
public class StarCoffee extends Beverage {
@Override
public String getDescription() {
return "StarCoffee";
}
@Override
public double getCost() {
return 12.0;
}
}
package com.gavin.model;
public class EnCoffee extends Beverage {
@Override
public String getDescription() {
return "EnCoffee";
}
@Override
public double getCost() {
return 5.0;
}
}
创建装饰者,代码如下:
package com.gavin.model;
public abstract class Decrator extends Beverage {
Beverage beverage;
@Override
public String getDescription() {
return beverage.getDescription();
}
@Override
public double getCost() {
return beverage.getCost();
}
}
装饰实现者:
package com.gavin.model;
public class Milk extends Decrator {
public Milk(Beverage beverage) {
this.beverage = beverage;
}
@Override
public String getDescription() {
return super.getDescription() + "添加milk";
}
@Override
public double getCost() {
return super.getCost() + 3.0;
}
}
package com.gavin.model;
public class Sugar extends Decrator {
public Sugar(Beverage beverage) {
this.beverage = beverage;
}
@Override
public String getDescription() {
return super.getDescription() + "添加sugar";
}
@Override
public double getCost() {
return super.getCost() + 3.0;
}
}
最后新建一个测试类:
package com.gavin.model;
public class Test {
public static void main(String[] args) {
Beverage beverage1 = new StarCoffee();
Beverage beverage2 = new EnCoffee();
Beverage beverage3 = new Milk(beverage1);
Beverage beverage4 = new Sugar(beverage2);
System.out.println(beverage3.getDescription() + beverage3.getCost());
System.out.println(beverage4.getDescription() + beverage4.getCost());
}
}
测试结果如下:
StarCoffee添加milk15.0
EnCoffee添加sugar8.0