大话设计模式读书笔记15----组合模式(Composite)

组合模式(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);
        }
    }
}


 

你可能感兴趣的:(设计模式)