[Design Pattern] Simple Factory

簡單工廠模式 - Simple Factory

可以根據所傳入的不同參數,取得不同的類別物件。
  • 靜態工廠模式
  • 共同的父類別

自訂介面 Interface

public Interface IFactory
{
    string GetType();
}

實作繼承的各產物

public class Honda : IFactory
    {
        private readonly string _vendor;

        public Honda(string vendor)
        {
            this._vendor = vendor;
        }

        public string GetType()
        {
            Console.WriteLine($"Vendor : {this._vendor}");
            return _vendor;
        }
    }

public class Toyota : IFactory
    {
        private readonly string _vendor;

        public Toyota(string vendor)
        {
            this._vendor = vendor;
        }

        public string GetType()
        {
            Console.WriteLine($"Vendor : {this._vendor}");
            return _vendor;
        }
    }

產物

透過簡單工廠方法,將從工廠自動將產物生產出。

public class CarFactory
    {
        public static IFactory carFactory(string type)
        {
            switch (type)
            {
                case "Honda": return new Honda(type);
                case "Toyota": return new Toyota(type);
                default: return null;
            }
        }
    }

主程式

class Program
    {
        static void Main(string[] args)
        {
            IFactory car1 = CarFactory.carFactory("Honda");
            IFactory car2 = CarFactory.carFactory("Toyota");
            car1.GetType();
            car2.GetType();
            Console.WriteLine("Hello World!");
            Console.ReadLine();
        }
    }

留言

這個網誌中的熱門文章

[Tools] GCOV & LCOV 初探

Quilt Patch 管理操作方法

[C#]C# Coding 規則