CSDN博客

img 2002pine

Design Pattern 3-Composite

发表于2004/9/25 17:10:00  625人阅读

using System;

namespace Pattern
{
 /// <summary>
 /// Summary description for Class1.
 /// </summary>
 public class CompositeEquipment:Equipment
 {
  System.Collections.ArrayList list=new System.Collections.ArrayList();
  public CompositeEquipment (string name) :base(name)
  {
   //
   // TODO: Add constructor logic here
   //
  }
  public bool add(Equipment equipment)
  {
   list.Add(equipment);
   return base.add(equipment);
  }
  public bool remove(Equipment equipment)
  {
   list.Remove (equipment);
   return base.remove(equipment);
  }
  public override double discountPrice()
  {
   double res=0;
   foreach(Equipment e in list)
   {
               res+=e.discountPrice();
   }
   return res;
  }
  public override double netPrice()
  {
   double res=0;
   foreach(Equipment e in list)
   {
    res+=e.netPrice();
   }
   return res;
  }


 }

 public abstract class Equipment
 {
  private string name;   //实价 
  public abstract double netPrice();  //折扣价格 
  public abstract double discountPrice();  //增加部件方法  
  public bool add(Equipment equipment) { return false; }  //删除部件方法
  public bool remove(Equipment equipment) { return false; }  //注意这里,这里就提供一种用于访问组合体类的部件方法。  
  
  public Equipment( string name) { this.name=name; }
  public string getName(){return this.name;}
 }

 public class eq1:Equipment
 {
  public eq1(string name) :base(name)
  {
  }
  public override double discountPrice()
  {
  
   return 80;
  }
  public override double netPrice()
  {
   
   return 100;
  }

 }

 public class eq2:Equipment
 {
  public eq2(string name) :base(name)
  {
  }
  public override double discountPrice()
  {
  
   return 800;
  }
  public override double netPrice()
  {
   
   return 1000;
  }

 }

}

    //合成模式 
   Equipment e1=new eq1("eq1");
 Equipment e2=new eq2("eq2");
  CompositeEquipment s=new CompositeEquipment("s");
   s.add(e1);
   s.add(e2);
  Console.WriteLine(s.netPrice().ToString());
  Console.WriteLine(s.discountPrice ().ToString());
      Console.WriteLine(s.getName());
  Console.WriteLine(e1.getName());
  Console.WriteLine(e2.getName());

阅读全文
0 0

相关文章推荐

img
取 消
img