Head First装饰模式(Decorator)
来源:互联网 发布:杯子知乎 编辑:程序博客网 时间:2024/05/01 05:10
装饰者模式是动态的将责任附加到另一个对象上,由这个对象负责;这个装饰与被装饰的组件接口一致,因此对使用该组件的客户透明;其中的关键点是装饰者可以在所委托被装饰者的行为之前和之后,加上自己的行为,已达到特点的目的。
代码如下:
-------------Component
//装饰者模式一般使用抽象类
public abstract class Beverage {
String description = "unknown beverage" ;
public String getDescription(){
return description ;
}
public abstract double cost();
}
------------Decorator(持有一个指向Component的指针,并与Component接口一致)
public abstract class CondimentDecorator extends Beverage{
//要求所有的调料都要重新实现这个方法;
public abstract String getDescription();
}
----------------ConcreteComponent(定义一些对象,可以给其添加职责)
//浓缩咖啡
public class Espresso extends Beverage{
//为了重新设置饮料的描述,这里在构造方法中重置继承自基类的变量
public Espresso(){
description = "Espresso" ;
}
public double cost() {
return 1.99;
}
}
//深焙咖啡
public class DarkRoast extends Beverage{
public DarkRoast(){
description = "Dark Roast Coffee" ;
}
public double cost() {
return 0.99;
}
}
-------------ConcreteDecorator
//摩卡调料
public class Mocha extends CondimentDecorator{
Beverage beverage ;
//想办法让被装饰者(饮料)记录到实例变量中
public Mocha(Beverage b){
this .beverage = b;
}
//装饰者还要能描述其装饰的对象的特点
@Override
public String getDescription() {
return beverage .getDescription() + ", Mocha";
}
@Override
public double cost() {
return beverage .cost() + 0.20;
}
}
//豆浆调料
public class Soy extends CondimentDecorator{
Beverage beverage;
public Soy(Beverage b){
this .beverage = b;
}
@Override
public String getDescription() {
return beverage .getDescription() + ", Soy";
}
@Override
public double cost() {
return beverage .cost() + 0.15;
}
}
-----------------测试
public class StarbuzzCoffee {
public static void main(String[] args) {
Beverage b = new Espresso();
System. out .println(b.getDescription() + ", $" +b.cost());
Beverage b2 = new DarkRoast();
b2 = new Mocha(b2 );
b2 = new Mocha(b2 );
b2 = new Soy(b2 );
System. out .println(b2.getDescription() + ", $" +b2.cost());
}
}
0 0
- Head First装饰模式(Decorator)
- Head First 设计模式 (三) 装饰者模式(decorator pattern) C++实现
- Head First设计模式C++实现--第三章:装饰者(Decorator)模式
- Head First设计模式之装饰者模式(Decorator Pattern)
- 《Head First Design Patterns》笔记三:装饰者模式(Decorator Pattern)
- Head First 设计模式——装饰器(Decorator Pattern)——Python实现
- Head First 装饰模式
- Head First 设计模式——装饰者模式(Decorator Pattern)
- Head First装饰者模式
- Head First: 装饰者模式
- Head First---装饰者模式
- Head First 装饰者模式
- 【Head First设计模式】-Decorator模式
- 【Head First设计模式】-Decorator模式
- Head First设计模式:(三)装饰者模式
- Head First 设计模式(3)- 装饰者模式 笔记
- Head First 设计模式(3):装饰者模式
- Head First 设计模式(四)装饰者模式
- android 运用线程
- Linux 学习笔记 -- 第二部分 Linux 文件、目录与磁盘格式 -- 第7章 Linux 文件与目录管理
- 最迷你wifi智能插座
- appium踩过的坑
- Myeclipse的workspace配置文件浅谈 .
- Head First装饰模式(Decorator)
- chapter11 separate Compilition and Namespaces(part1)
- android模拟器按键对应的键盘按键
- 改错题_102
- 在嵌入式Linux系统(OK6410)中移植Boa 服务器
- Luasocket 服务器,客户端简单实例
- 好久没做asp了,这个天都在做asp,今天做asp操作xml,找了些资料才做出来
- 改错题_103
- poj 3253 Fence Repair(Huffman问题,优先队列priority_queue)