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

using System;
using System.Collections.Generic;
using System.Text;

namespace Composite
{
    
class Program
    {
        
static void Main(string[] args)
        {
            ConcreteCompany root 
= new ConcreteCompany("北京总公司");
            root.Add(
new HRDepartment("总公司人力资源部"));
            ConcreteCompany comp 
= new ConcreteCompany("上海华东分公司");
            comp.Add(
new HRDepartment("上海华东分公司人力资源部"));
            root.Add(comp);
            Console.WriteLine(
"结构图:");
            root.Display(
1);
            Console.WriteLine(
"职责:");
            root.LineOfDuty();
            Console.ReadLine();

        }
    }
    
//定义抽象的公司类
    abstract class Company
    {
        
private string _name;

        
protected string Name
        {
            
get { return _name; }
            
set { _name = value; }
        }
        
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 ConcreteCompany : Company
    {
        
private List<Company> children = new List<Company>();
        
public ConcreteCompany(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 component in children)
            {
                component.LineOfDuty();
            }
        }
    }
    
class HRDepartment : Company
    {
        
public HRDepartment(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);
        }
    }
}

相关文章:

  • 2021-09-08
  • 2022-01-10
  • 2022-12-23
  • 2022-12-23
  • 2021-06-23
  • 2021-10-29
猜你喜欢
  • 2022-01-02
  • 2021-11-12
  • 2022-12-23
  • 2021-08-08
  • 2022-01-10
  • 2021-12-12
相关资源
相似解决方案