装饰者模式就是在不动原来代码的情况下为原来的对象动态的添加某些修饰,主要就是原本扩展功能可以用继承来实现,可是我们也可以用组合的形式来实现扩展。
package com.djk.design.Decorator;
/**
* 装饰者模式
* @author djk
*
*/
public class DecoratorTest
{
public static void main(String[] args)
{
CommonCoffee coffee = new BlackCoffee();
System.out.println("咖啡的名称:"+coffee.getDescription());
System.out.println("咖啡的价格:"+coffee.cost());
}
}
/**
* coffee基类
* @author djk
*
*/
abstract class CommonCoffee
{
private String description;
/**
* 咖啡的价格
*/
public abstract double cost();
public String getDescription() {
return description;
}
public void setDescription(String description) {
this.description = description;
}
}
/**
* 黑咖啡
* @author djk
*
*/
class BlackCoffee extends CommonCoffee
{
public BlackCoffee()
{
super.setDescription("blackCoffee");
}
/**
* 黑咖啡的价格1元
*/
@Override
public double cost()
{
return 1.0;
}
}
这里是一个简单的咖啡类,有一个具体的实现类黑咖啡,黑咖啡的价格是1.0元,不过有的时候会在黑咖啡里面加一点牛奶,不过加了牛奶后价格肯定要比以前的纯黑咖啡要高,此时我们会想写一个类继承此黑咖啡在覆盖cost方法加上自己的价格,可是如果后续还要在黑咖啡里面加糖或别的东西的话则继承会一直延续下去。此时我们就可以利用装饰模式来解决这个问题也说明了继承能完成的事利用组合也能完成(优先使用组合,再考虑继承。继承只能单继承,继承在编译的时候就静态确定了,而组合是在运行时动动态决定的):
package com.djk.design.Decorator;
/**
* 装饰者模式
* @author djk
*
*/
public class DecoratorTest
{
public static void main(String[] args)
{
CommonCoffee coffee = new BlackCoffee();
CoffeeCompent coffeeCompent = new Milk(coffee);
coffeeCompent = new Sugar(coffeeCompent);
System.out.println("咖啡的名称:"+coffeeCompent.getDescription());
System.out.println("咖啡的价格:"+coffeeCompent.cost());
}
}
/**
* coffee基类
* @author djk
*
*/
abstract class CommonCoffee
{
private String description;
/**
* 咖啡的价格
*/
public double cost()
{
return 0.0;
}
public String getDescription() {
return description;
}
public void setDescription(String description) {
this.description = description;
}
}
/**
* 黑咖啡
* @author djk
*
*/
class BlackCoffee extends CommonCoffee
{
public BlackCoffee()
{
super.setDescription("blackCoffee");
}
/**
* 黑咖啡的价格1元
*/
@Override
public double cost()
{
return 1.0;
}
}
/**
* 抽象装饰类
* @author djk
*
*/
abstract class CoffeeCompent extends CommonCoffee
{
}
/**
* 牛奶
* @author djk
*
*/
class Milk extends CoffeeCompent
{
private CommonCoffee coffee;
public Milk(CommonCoffee coffee)
{
this.coffee = coffee;
}
@Override
public String getDescription() {
return coffee.getDescription()+"milk";
}
/**
* 牛奶的咖啡要在原来的基础上加0.5元
*/
@Override
public double cost()
{
return coffee.cost() + 0.5;
}
}
/**
* 糖
* @author djk
*
*/
class Sugar extends CoffeeCompent
{
private CommonCoffee coffee;
public Sugar(CommonCoffee coffee)
{
this.coffee = coffee;
}
@Override
public String getDescription()
{
return coffee.getDescription()+"sugar";
}
/**
* 加糖的也要加5毛
*/
@Override
public double cost()
{
return coffee.cost()+0.5;
}
}
此时在黑牛奶的基础上做了扩展加了唐糖和牛奶,如果要加别的话只要改成别的装饰即可,这样扩展性比继承要好。。。