1. 程式人生 > 實用技巧 >【設計模式】8.組合模式

【設計模式】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); } } } }