设计模式-装饰者模式
来源:互联网 发布:celtx剧本写作软件 编辑:程序博客网 时间:2024/06/18 13:46
装饰器模式
装饰器模式(Decorator
Pattern)允许向一个现有的对象添加新的功能,同时又不改变其结构。这种类型的设计模式属于结构型模式,它是作为现有的类的一个包装。
这种模式创建了一个装饰类,用来包装原有的类,并在保持类方法签名完整性的前提下,提供了额外的功能。
我们通过下面的实例来演示装饰器模式的用法。其中,我们将把一个形状装饰上不同的颜色,同时又不改变形状类。
优点:装饰类和被装饰类可以独立发展,不会相互耦合,装饰模式是继承的一个替代模式,装饰模式可以动态扩展一个实现类的功能。
缺点:多层装饰比较复杂。
使用场景: 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 { @Override public float cost() { // TODO Auto-generated method stub return super.getPrice(); }}
public class LongBlack extends Coffee{ public LongBlack() { super.setDescription("LongBlack"); super.setPrice(6.0f); }}
public class Decorator extends Drink { private Drink Obj; public Decorator(Drink Obj){ this.Obj=Obj; }; @Override public float cost() { // TODO Auto-generated method stub return super.getPrice()+Obj.cost(); } @Override public String getDescription() { return super.description+"-"+super.getPrice()+"&&"+Obj.getDescription(); } }
public class Chocolate extends Decorator { public Chocolate(Drink Obj) { super(Obj); // TODO Auto-generated constructor stub super.setDescription("Chocolate"); super.setPrice(3.0f); }}
public class Milk extends Decorator { public Milk(Drink Obj) { super(Obj); // TODO Auto-generated constructor stub super.setDescription("Milk"); super.setPrice(2.0f); }}
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()); }
0 0
- 设计模式-装饰者模式
- 设计模式:装饰者模式
- 设计模式:装饰者模式
- 设计模式: 装饰者模式
- 设计模式--装饰者模式
- 设计模式-装饰者模式
- 设计模式--装饰者模式
- 设计模式-装饰者模式
- 设计模式------------装饰者模式
- 设计模式--装饰者模式
- 设计模式:装饰者模式
- 设计模式-装饰者模式
- 设计模式-装饰者模式
- 设计模式-装饰者模式
- 设计模式--装饰者模式
- 【设计模式】装饰者模式
- 设计模式---装饰者模式
- 设计模式 装饰者模式
- 循环队列的优点缺点
- 验证哥德巴赫猜想
- Scala入门之面向接口编程
- JZOJ4588. 【NOI2016模拟7.7】冷战 + 按秩合并讲解
- codeforces-702D-Road to Post Office
- 设计模式-装饰者模式
- eclipse怎么查看开发包jar里源代码
- Linux -- 档案与目录管理
- Android自定义权限
- 【整理】getElementByID,getElementsByName,getElemtsByTagName的区别
- [Kubernetes]Docker的overlay网络模型
- java语言基础入门——多线程
- UNIX网络编程笔记(11)—UNIX域套接字
- Android高效的加载大图片