装饰者设计模式 -C#
来源:互联网 发布:red flag linux 8.0 编辑:程序博客网 时间:2024/06/06 22:45
参考《Head First设计模式》
装饰者模式定义:
动态地将责任附加到对象上,若要扩展功能,装饰者提供了比继承更有弹性的替代方案。
主要思想:
将装饰者与被装饰者自同一个超类型;
可以用一个或多个装饰者包装一个对象;
装饰者与被装饰者有相同的超类型,因而在任何需要原始对象(被包装的)的场合,可以用装饰过的对象代替它;
装饰者可以在被装饰者的行为前/后,添加自己的行为,以达到特定目的;
对象可以在任何时候被装饰,所以可以在运行时动态地装饰对象;
public abstract class Beverage { public string description = "UnKnown Beverage."; public abstract double cost(); public abstract string getDescription(); }
public abstract class Condiment:Beverage { }
class Mocha : Condiment { Beverage beverage; public Mocha(Beverage beverage) { this.beverage = beverage; } public override string getDescription() { return this.beverage.getDescription() + " , Mocha"; } public override double cost() { return this.beverage.cost() + 0.2; } }
public class Soy:Condiment { Beverage beverage; public Soy(Beverage beverage) { this.beverage = beverage; } public override string getDescription() { return this.beverage.getDescription() + " , Soy"; } public override double cost() { return this.beverage.cost() + 0.4; } }
public class Espresso:Beverage { public Espresso() { this.description = "Espresso"; } public override double cost() { return 1.99; } public override string getDescription() { return this.description; } }
class HouseBlend : Beverage { public HouseBlend() { this.description = "House Blend"; } public override double cost() { return 1.01; } public override string getDescription() { return string.Empty; } }
测试代码:
static void Main(string[] args) { Beverage beverage = new Espresso(); Console.WriteLine(beverage.getDescription()); Console.WriteLine(beverage.cost()); Beverage beverage2 = new Espresso(); beverage2 = new Mocha(beverage2); beverage2 = new Soy(beverage2); Console.WriteLine(beverage2.getDescription()); Console.WriteLine(beverage2.cost()); Console.ReadKey(); }
运行结果:
Espresso
1.99
Espresso, Mocha, Soy
2.59
阅读全文
0 0
- 装饰者设计模式 -C#
- 【C#设计模式-装饰者模式】
- C#设计模式之《装饰者模式》
- C#设计模式之装饰者
- c#设计模式--装饰模式
- C#设计模式之装饰者模式(Decorator Pattern)
- C#设计模式(七)装饰者模式
- C#装饰者模式
- 装饰者设计模式
- 设计模式 - 装饰者
- 装饰者设计模式
- 装饰者设计模式
- 装饰者设计模式
- 装饰者设计模式
- 装饰者设计模式
- 装饰者设计模式
- 装饰者设计模式
- 装饰者设计模式
- MongoDB学习(一)MongoDB常用命令
- Java获取视频时长、宽高、文件大小、格式、并截图做封面
- Redis数据结构详解之Zset
- 浅谈UI设计师的职业发展
- Spark Streaming(下)--实时流计算Spark Streaming实战
- 装饰者设计模式 -C#
- Simple Selection Sort(简单选择排序)
- 管道理解
- 裸机安装Linux系统,Centos系统的安装
- http://doc.okbase.net/29165999/archive/81414.html
- 有了这8条建议,你的排版设计会更优秀
- 如何进行高级的页面关键字研究
- 会声会影如何批量添加转场?
- VMware Workstation Pro安装教程图文详解