2013年9月23日 星期一

設計模式 (三) Abstract Factory

觀察 main function 可得知
使用者不需要關心 他所創造的是哪個OEM工廠
他只需要知道他目前需要製造的東西是甚麼
好處是 如果使用者之後需要新增OEM工廠
只需要再新增一個class就好
而不需要把code寫在main裡面造成維護或讀code上面的困難
下面的範圍實做兩個OEM工廠
兩個OEM工廠都可以製作手機以及電話


  
    
    abstract class IPhoneBase
    {
        public abstract void Dial();
    }

    abstract class INoteBook
    {
        public abstract void PowerOn();
    }

    interface IFactory
    {
        IPhoneBase CreatePhone();
        INoteBook CreateNoteBook();
    }

    class SamsugPhone : IPhoneBase
    {
        public override void Dial()
        {
            Console.WriteLine("Samsug Phone Is Dialing");
        } 
    }

    class AsuPhone : IPhoneBase
    {
        public override void Dial()
        {
            Console.WriteLine("Asu Phone Is Dialing");
        }
    }

    class SamsugNotBook : INoteBook
    {
        public override void PowerOn()
        {
            Console.WriteLine("Samsug NoteBook Is PowerOn");
        }
    }

    class AsuNotBook : INoteBook
    {
        public override void PowerOn()
        {
            Console.WriteLine("Asu NoteBook Is PowerOn");
        }
    }

    class AsuFactory : IFactory
    {
        public IPhoneBase CreatePhone()
        {
            return new AsuPhone();
        }
        public INoteBook CreateNoteBook()
        {
            return new AsuNotBook();
        }
    }

    class SamsugFactory : IFactory
    {
        public IPhoneBase CreatePhone()
        {
            return new SamsugPhone();
        }
        public INoteBook CreateNoteBook()
        {
            return new SamsugNotBook();
        }
    }

    class OEMFactory
    {
        public IFactory GetFactory(string name)
        {
            if (name == "Samsug")
            {
                return new SamsugFactory();
            }
            else if (name == "Asu")
            {
                return new AsuFactory();
            }
            else
                return null;
        }
    }



    class Program
    {
        static void Main(string[] args)
        {
            OEMFactory Factory = new OEMFactory();
            IFactory AsuFactory = Factory.GetFactory("Asu");
            AsuFactory.CreatePhone().Dial();
            AsuFactory.CreateNoteBook().PowerOn();

            IFactory SamsungFactory = Factory.GetFactory("Samsug");
            SamsugFactory.CreatePhone().Dial();
            SamsugFactory.CreateNoteBook().PowerOn();
            Console.ReadKey();
        }
    }
優點
1.產品從代碼中被分離出來
2.容易改變產品的系列
3.可拿到建立OEM系列的產品族的接口
缺點
1.當要新增OEM工廠裡的產品時須對所有的 OEM class 做修改

沒有留言:

張貼留言