泡泡

              宠辱不惊-闲看庭前花开花落
                           去留无意-漫观天外云展云舒
  首页  :: 新随笔  :: 联系 :: 订阅 订阅  :: 管理

09)Decorator

Posted on 2007-09-19 15:07  AlanPaoPao  阅读(212)  评论(0)    收藏  举报
    装饰模式的目的是: 动态地给一个对象添加一些额外的职责(比生成子类更为灵活)
    实例代码:
interface IItemLibrary
{
  
void Display();
  
int ItemCount getset; }
  
double Price getset; }
}

abstract class ItemLibrary : IItemLibrary
{
  
protected int count;
  
protected double price;
  
public double Price
  
{
    
get return price; }
    
set { price = value; }
  }

  
public int ItemCount
  
{
    
get return count; }
    
set { count = value; }
  }

  
public abstract void Display();
}

class Curtain : ItemLibrary
{
  
private string mode;
  
private string name;
  
public Curtain(string mode, string name, int count,double price)
  
{
    
this.mode = mode;
    
this.name = name;
    
this.count = count;
    
this.price = price;
  }

  
public override void Display()
  
{
    Console.WriteLine(
"窗帘 ------ ");
    Console.WriteLine(
" 样式: {0}", mode);
    Console.WriteLine(
" 名称: {0}", name);
    Console.WriteLine(
" 数量: {0}", count.ToString());
    Console.WriteLine(
" 价格: {0}", price.ToString());
  }

}

class Sofa : ItemLibrary
{
  
private string type;
  
private string color;
  
private string name;
  
public Sofa(string type, string color, string name, int count, double price)
  
{
    
this.type = type;
    
this.color = color;
    
this.name = name;
    
this.count = count;
    
this.price = price;
  }

  
public override void Display()
  
{
    Console.WriteLine(
"沙发 ------ ");
    Console.WriteLine(
" 类型: {0}", type);
    Console.WriteLine(
" 名称: {0}", name);
    Console.WriteLine(
" 颜色: {0}", color);
    Console.WriteLine(
" 数量: {0}", count.ToString());
    Console.WriteLine(
" 价格: {0}", price.ToString());
  }

}

abstract class Decorator : ItemLibrary
{
  
protected IItemLibrary iItem;
  
public Decorator(IItemLibrary libraryItem)
  
{
    
this.iItem = libraryItem;
  }

  
public override void Display()
  
{
    iItem.Display();
  }

}

class Rebate : Decorator
{
  
protected double agio;
  
public Rebate(IItemLibrary libraryItem,Double agio)
    : 
base(libraryItem)
  
{
    
this.agio = agio;
  }

  
public Double BuyItem(Int32 count)
  
{
    iItem.ItemCount 
-= count;
    
return count * iItem.Price * this.agio;
  }

  
public override void Display()
  
{
    
base.Display();
    Console.WriteLine(
"折扣率: " + agio.ToString());
  }

}

class MainApp
{
  
static void Main()
  
{
    IItemLibrary rome 
= new Curtain("罗马帘","ITEM00001",100,98.9);
    rome.Display();
    IItemLibrary smallSofa 
= new Sofa("三人沙发","红色","ITEM010101"405300);
    smallSofa.Display();
    Console.WriteLine(
"\nBegion Rebate:");
    Rebate rebate 
= new Rebate(smallSofa, 0.8);
    Console.WriteLine(
"购买{0}台沙发{1}钱:""5", rebate.BuyItem(5).ToString());
    Console.WriteLine(
"购买{0}台沙发{1}钱:""2", rebate.BuyItem(2).ToString());
    rebate.Display();
    Console.Read();
  }

}