1. 程式人生 > >工廠模式(簡單,配置檔案,反射,工廠方法,抽象)

工廠模式(簡單,配置檔案,反射,工廠方法,抽象)

2.工廠模式+配置檔案

using System.Configuration;
using System;
namespace DesignMode
{
    public class ConfigureFactory
    {
        private static string type = ConfigurationManager.AppSettings["TrafficType"];//讀取配置檔案
        public static TrafficInterface CreateInstance() {
            switch ((TrafficType)Enum.Parse(typeof(TrafficType),type))
            {
                case TrafficType.Car:
                    return new Car();
                case TrafficType.Train:
                    return new Train();
                case TrafficType.Airplane:
                    return new Airplane();
                default:
                    return null;
            }
        }

        public enum TrafficType {
            Car,
            Train,
            Airplane
        }
        
    }
}

在App.config的配置檔案如圖


加上配置檔案的好處,就是程式碼管理起來更加的容易,在茫茫的程式碼堆中需要修改的時候直接去找配置檔案就可以,雖然效能上有消耗是必然的。

3.工廠模式+反射機制

using System.Configuration;
using System;
namespace DesignMode
{
    public class ReflectFactory
    {
        private static string reflect = ConfigurationManager.AppSettings["TrafficReflect"];//讀取配置檔案
        public static TrafficInterface CreateInstance() {
            string assemblyName = reflect.Split(',')[0];
            string typeName = reflect.Split(',')[1];
            return (TrafficInterface)(Activator.CreateInstance(assemblyName, typeName).Unwrap());//反射去建立物件
        }        
    }
}

這個反射機制不用選擇開關,因為反射允許我們在編譯與執行時,可以載入程式程式碼的內部資訊,反射成本很高,效能消耗更大,但是程式碼也更加容易維護。

3.工廠方法


namespace DesignMode
{
    public class CarFactory:OnlyFactoryInterface
    {
        public TrafficInterface CreateInstance() {
            //TODO 在建立物件前拓展一些辦法
            return new Car();
        }
    }
}

namespace DesignMode
{
    public interface OnlyFactoryInterface
    {
        TrafficInterface CreateInstance();
    }
}
一個類有一個單單建立它的工廠類,這個有什麼好處呢?就像筆者上面註釋的,這個類建立前拓展一些辦法,也就是開閉原則,對於拓展開放修改封閉。

4.抽象工廠

namespace DesignMode
{
    public interface IFactoryInterface
    {
        TrafficInterface CreaateFirst();
        TrafficInterface CreateSecond();
        TrafficInterface CreateThird();
        TrafficInterface CreateFourth();
    }
}
using System;
namespace DesignMode
{
    class TrafficFactory : IFactoryInterface
    {
        public TrafficInterface CreaateFirst()
        {
            return new Car();
        }


        public TrafficInterface CreateSecond()
        {
            return new Train();
        } 


        public TrafficInterface CreateThird()
        {
            return new Airplane();
        }


        public TrafficInterface CreateFourth()
        {
            throw new NotImplementedException();
        }
    }
}

這個抽象工廠在專案修改或者新增的時候比較繁瑣,但是當有相同模組需要開發的時候,程式碼就可以完全重複使用,並且工廠模式都符合開閉原則。

每一個設計模式的出現都是為了使程式碼在這個專案更加容易維護和管理,不是每一個設計模式適合每一個專案。