[設計模式練習]享元模式

[設計模式練習]享元模式

當公司部門雇用員工的時候,以部門為出發點,實體化同部門一次,之後有新的員工被雇用只要調用原來的部門即可。

 

類別圖

FlyWeight

物件檔定義


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

namespace DesignModelTest.享元
{
    /// <summary>
    /// FlyWeight類別 : 部門
    /// </summary>
    abstract class CompanyDepartment
    {
        public abstract void Hire(Employee employee);
    }
    /// <summary>
    /// 外部類別 : 僱用員工
    /// </summary>
    public class Employee
    {
        private string _name;
        public string name
        {
            get{ return _name;}
        }
        public Employee(string name)
        {
            this._name = name;
        }   
    }
    /// <summary>
    /// ConcreteFlyWeight類別 : 部門實體
    /// </summary>
    class ConcreteCompanyDepartment : CompanyDepartment
    {
        private string name = string.Empty;
        public ConcreteCompanyDepartment(string name)
        {
            this.name = name;
        }
        public override void Hire(Employee employee)
        {
            Console.WriteLine("公司部門:{0} 雇用:{1}", this.name, employee.name);
        }
    }
    /// <summary>
    /// FlyweightFactory類別
    /// </summary>
    class CompanyDepartmentFactory
    {
        private Hashtable flyweights = new Hashtable();
        //將使用的部門用hashtable記錄下來,當同樣部門被使用時,直接從table找
        public CompanyDepartment GetCompanyDepartmentCategory(string depName)
        {
            if (!flyweights.ContainsKey(depName))
                flyweights.Add(depName, new ConcreteCompanyDepartment(depName));
            return ((CompanyDepartment)flyweights[depName]);
        }
        //記算實體化多少部門
        public int GetDepartmentCount()
        {
            return flyweights.Count;
        }
    }
}

用戶端程式碼


            DesignModelTest.享元.CompanyDepartmentFactory f = new DesignModelTest.享元.CompanyDepartmentFactory();
            //第一次調用實體化並將物件存入hashtable
            DesignModelTest.享元.CompanyDepartment department1 = f.GetCompanyDepartmentCategory("工程部");
            department1.Hire(new DesignModelTest.享元.Employee("阿貓"));
            //第二次調用並無實體化 直接取hashtable中的物件
            DesignModelTest.享元.CompanyDepartment department2 = f.GetCompanyDepartmentCategory("工程部");
            department2.Hire(new DesignModelTest.享元.Employee("阿狗"));
            DesignModelTest.享元.CompanyDepartment department3 = f.GetCompanyDepartmentCategory("客服部");
            department3.Hire(new DesignModelTest.享元.Employee("阿鼠"));
            //計算所有實體化物件總數
            Console.WriteLine("部門總數:{0}", f.GetDepartmentCount().ToString());
            Console.Read();
            #endregion

輸出結果

pic2