组合模式(composite)学习

来源(大话设计模式)

组合模式(composite):将对象组合成树形结构以表示‘部分-整体’的层次结构。组合模式使得用户对单个对象和组合对象的使用具有一致性。

当你发现需求中是体现部分和整体层次的结构的时候,以及你希望用户可以忽略组合对象与单个对象的不同,统一的使用组合结构中的所有对象时,就应该考虑使用组合模式。

 

abstract  class Company
  {
       protected string name;
       public Company(string name)
       {
           this.name = name;
       }
       public abstract void add(Company c);
       public abstract void remove(Company c);
       public abstract void display(int depth);
       public abstract void lineofduty();
  }
  class ConcreateCompany : Company
  {
      private List<Company> children = new List<Company>();
      public ConcreateCompany(string name)
          : base(name)
      { }
      public override void  add(Company c)
      {
          children.Add(c);
      }
      public override void remove(Company c)
      {
          children.Remove(c);
      }
      public override void display(int depth)
      {
          Console.WriteLine(new string('-', depth) + name);
          foreach (Company component in children)
          {
              component.display(depth + 2);
          }
      }
      //履行职责
      public override void lineofduty()
      {
          foreach (Company comonent in children)
          {
              comonent.lineofduty();
          }
      }
  }
  //人力资源部
  class HR : Company
  {
      public HR(string name)
          : base(name)
      { }
      public override void add(Company c)
      {
          throw new Exception("The method or operation is not implemented.");
      }
      public override void remove(Company c)
      {
          throw new Exception("The method or operation is not implemented.");
      }
      public override void display(int depth)
      {
          Console.WriteLine(new string('-', depth) + name);
      }
      public override void lineofduty()
      {
          Console.WriteLine("{0} 员工招聘培训管理", name);
      }
  }
  //Finance财务部
  class Finance : Company
  {
      public Finance(string name)
          : base(name)
      { }
      public override void add(Company c)
      {
          throw new Exception("The method or operation is not implemented.");
      }
      public override void remove(Company c)
      {
          throw new Exception("The method or operation is not implemented.");
      }
      public override void display(int depth)
      {
          Console.WriteLine(new string('-', depth) + name);
      }
      public override void lineofduty()
      {
          Console.WriteLine("{0} 公司财务收支管理", name);
      }
  }

你可能感兴趣的:(组合模式)