java设计模式:装饰者模式

来源:互联网 发布:linux if语句使用方法 编辑:程序博客网 时间:2024/06/01 09:16

1.装饰模式就是给一个对象增加一些新的功能,而且是动态的,要求装饰
对象和被装饰对象实现同一个接口,装饰对象持有被装饰对象的实例.
2.装饰器模式的应用场景:扩展一个类的功能.
3.整体模式的设计;
(1).装饰者和被装饰者都要继承的抽象类Drink()
(2).装饰者:Decorator(), 和继承装饰者的具体实现类
(3).被装饰的对象Coffee(), 和继承Coffee的对象
4.具体代码:
(1).
/**
* 装饰对象 和 被装饰对象 继承的同一个的类 即:装饰者:Decorator, 被装饰着:Drink
*/
public abstract class Drink {

public String description="";private float price=0f;;public void setDescription(String description){    this.description=description;}public String getDescription(){    return description+"-"+this.getPrice();}public float getPrice(){    return price;}public void setPrice(float price){    this.price=price;}public abstract float cost();

}
(2).
/**
* 被装饰者– 继承Drink实体类 和Decorator一样都是继承Drink实体类
*/
public class Coffee extends Drink {

@Overridepublic float cost() {    return super.getPrice();}

}
具体的被装饰的对象:
public class Decaf extends Coffee {

public Decaf(){    super.setDescription("Decaf");    super.setPrice(3.0f);}

}
public class Espresso extends Coffee{

public Espresso(){    super.setDescription("Espresso");    super.setPrice(4.0f);}

}
public class LongBlack extends Coffee{

public LongBlack(){    super.setDescription("LongBlack");    super.setPrice(6.0f);}

}
等等……….

(3).
/**
* 装饰者– 继承Drink实体类 和Coffe一样都是继承Drink实体类
*/
public class Decorator extends Drink {

private Drink Obj;public Decorator(Drink Obj){    this.Obj=Obj;};@Overridepublic float cost() {    return super.getPrice()+Obj.cost();}@Overridepublic String getDescription(){    return super.description+"-"+super.getPrice()+"&&"+Obj.getDescription();}}

//具体继承的
public class Milk extends Decorator {

public Milk(Drink Obj) {    super(Obj);    super.setDescription("Milk");    super.setPrice(2.0f);}

}
public class Chocolate extends Decorator {

public Chocolate(Drink Obj) {    super(Obj);    super.setDescription("Chocolate");    super.setPrice(3.0f);}

}
public class Soy extends Decorator {

public Soy(Drink Obj) {    super(Obj);    // TODO Auto-generated constructor stub    super.setDescription("Soy");    super.setPrice(1.5f);}

}

测试:
public static void main(String[] args) {

    Drink order;    order=new Decaf();    System.out.println("order1 price:"+order.cost());    System.out.println("order1 desc:"+order.getDescription());    System.out.println("****************");    order=new LongBlack();    order=new Milk(order);    order=new Chocolate(order);    order=new Chocolate(order);    System.out.println("order2 price:"+order.cost());    System.out.println("order2 desc:"+order.getDescription());}