Decorator Pattern (装饰者模式)之星巴克的咖啡(C#源代码)

 
  1. using System;
  2. using System.Collections.Generic;
  3. using System.Linq;
  4. using System.Text;
  5. namespace Decker
  6. {
  7.     class CRunMain
  8.     {
  9.         static void Main(string[] args)
  10.         {
  11.             CBeverage objBev = new CEspresso();
  12.             CBeverage objBev2 = null;
  13.             Console.WriteLine(objBev.GetDescription() + "$" + objBev.Cost());
  14.             objBev2 = new CHouseBlend();
  15.             objBev2 = new CMocha(objBev2);
  16.             objBev2 = new CMocha(objBev2);
  17.             objBev2 = new CMocha(objBev2);
  18.             Console.WriteLine(objBev2.GetDescription() + "$" + objBev2.Cost());
  19.         }
  20.     };
  21.     //饮料
  22.     public abstract class CBeverage
  23.     {
  24.         public virtual string GetDescription()
  25.         {
  26.             return this.m_strDescription;
  27.         }
  28.         public abstract double Cost();
  29.         protected string m_strDescription;
  30.     };
  31.     public abstract class CCondimentDecortor : CBeverage
  32.     {
  33.         public abstract string GetDescription();
  34.     };
  35.     public class CEspresso : CBeverage
  36.     {
  37.         public CEspresso()
  38.         {
  39.             this.m_strDescription = "Espresso";
  40.         }
  41.         public override double Cost()
  42.         {
  43.             return 1.99;
  44.         }
  45.     };
  46.     public class CHouseBlend : CBeverage
  47.     {
  48.         public CHouseBlend()
  49.         {
  50.             this.m_strDescription = "House blend coffee";
  51.         }
  52.         public override double Cost()
  53.         {
  54.             return 0.89;
  55.         }
  56.     };
  57.     //调料
  58.     public class CMocha : CCondimentDecortor
  59.     {
  60.         public CMocha(CBeverage objBev)
  61.         {
  62.             this.m_objBev = objBev;
  63.             this.m_strDescription = this.GetDescription();
  64.         }
  65.         public override string GetDescription()
  66.         {
  67.             return this.m_objBev.GetDescription() + ", Mocha";
  68.         }
  69.         public override double Cost()
  70.         {
  71.             if (null == this.m_objBev)
  72.             {
  73.                 throw new Exception("null == obj");
  74.             }
  75.             return 0.2 + this.m_objBev.Cost();
  76.         }
  77.         private CBeverage m_objBev;
  78.     };
  79. }
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值