【设计模式】8.组合模式

说明:树形结构的类对象,适合做文件夹架构

实现:

public class Employee
    {
        public int id { get; set; }
        public string name { get; set; }
        public string job { get; set; }
        public List<Employee> empList;

        public Employee(int _id,string _name,string _job)
        {
            id = _id;
            name = _name;
            job = _job;
            empList = new List<Employee>();
        }

        public void add(Employee model)
        {
            empList.Add(model);
        }

        public void remove(Employee model)
        {
            empList.Remove(model);
        }

        public List<Employee> getempList()
        {
            return empList;
        }

        public String toString()
        {
            return ("Employee:[id:" + id + ",name:" + name + ",job:"+job+"]");
        }
    }

    public class test
    {
        public void start()
        {
            //1级
            Employee CEO = new Employee(0,"陈一","CEO");
            //2级
            Employee emp2 = new Employee(1, "李二", "总监");
            //3级
            Employee emp3 = new Employee(2, "王三", "经理");

            CEO.add(emp2);
            emp2.add(emp3);

            Console.Write(CEO);
            foreach(Employee e in emp2.getempList())
            {
                Console.Write(e);
                foreach(Employee e2 in emp3.getempList())
                {
                    Console.Write(e2);
                }
            }
        }
    }
原文地址:https://www.cnblogs.com/laokchen/p/13534751.html