java 开发模式之三 : 装饰者模式

来源:互联网 发布:matlab二分法求解编程 编辑:程序博客网 时间:2024/06/06 04:47

原理或定義

动态地给一个对象添加一些额外的职责,就增加功能来说,装饰模式比生成子类更为灵活。

不必改变原类文件和使用继承的情况下,动态的扩展一个对象的功能。它是通过创建一个包装对象,也就是装饰来包裹真实的对

特点结构

1) 装饰对象和真实对象有相同的接口,这样客户端对象就可以和真实对象相同的方式和装饰对象交互。
2)装饰对象包含一个真实对象的引用。
3)装饰对象接受所有来自客户端的请求,它把这些请求转发给真实的对象。
4)装饰对象可以在转发这些请求以前或以后增加一些附加功能。这样就确保了在运行时,不用修改给定对象的结构就可以在外部增加附加的功能。在面向对象的设计中,通常是通过继承来实现对给定类的功能扩展

類圖

案例和代碼

本模式用咖啡馆订单系统项目作为示例

咖啡馆订单项目:
1)咖啡种类:Espresso、ShortBlack、LongBlack、Decaf
2)调料:Milk、Soy、Chocolate

一个差的方案:



一个好一点的设计方案:



有些问题
1)增删调料种类
2)添加多份问题


装饰者模式设计的方案:


饮品抽象类

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();}


咖啡基类

public  class Coffee extends Drink {@Overridepublic float cost() {// TODO Auto-generated method stubreturn 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 Decorator extends Drink {private Drink Obj;public Decorator(Drink Obj){this.Obj=Obj;};@Overridepublic float cost() {// TODO Auto-generated method stubreturn super.getPrice()+Obj.cost();}@Overridepublic String getDescription(){return super.description+"-"+super.getPrice()+"&&"+Obj.getDescription();}}

调味子类(装饰者具体类)

public class Chocolate extends Decorator {public Chocolate(Drink Obj) {super(Obj);// TODO Auto-generated constructor stubsuper.setDescription("Chocolate");super.setPrice(3.0f);}}public class Milk extends Decorator {public Milk(Drink Obj) {super(Obj);// TODO Auto-generated constructor stubsuper.setDescription("Milk");super.setPrice(2.0f);}}public class Soy extends Decorator {public Soy(Drink Obj) {super(Obj);// TODO Auto-generated constructor stubsuper.setDescription("Soy");super.setPrice(1.5f);}}

管理类 / 测试方法

public class CoffeeBar {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());}}

装饰者模式下的订单:2份巧克力+一份牛奶的LongBlack



使用場景

1、需要扩展一个类的功能。

   2、动态的为对象增加功能,而且还能动态撤销。(继承不能做到这一点,不能动态增删)

優缺點

主要优点有:

1)装饰模式与继承关系的目的都是扩展对象功能,但是装饰模式比继承更多的灵活性。
2)通过使用不同的具体装饰类以及装饰类的排列组合,可以创造出很多不同行为的组合。

 

缺点主要有

1)这种比继承更加灵活机动的特性,也同时意味着更加多的复杂性。
2)装饰模式是针对抽象组件(Component)类型编程。但是,如果你要针对具体组件编程时,就应该重新思考你的应用架构,以及装饰者是否适合。当然也可以改变Component接口,增加新的公开的行为,实现"半透明"的装饰者模式。在实际项目中要做出最佳选择。

原创粉丝点击