設計模式筆記:簡單工廠模式(Simple Factory)

1. 簡單工廠模式簡介

1.1 定義

  簡單工廠模式:定義一個Factory類,能夠根據參數的不一樣返回不一樣類的實例,被建立的實例一般有共同的父類。設計模式

  簡單工廠模式:只須要一個Factory類。ide

  簡單工廠模式:又稱爲靜態工廠模式(Static Factory Pattern),Factory類爲靜態類或包含靜態方法spa

  簡單工廠模式:不屬於23種GOF設計模式。設計

  簡單工廠模式:實質是由一個工廠類根據傳入的參數,動態決定應該建立哪個產品類實例。3d

1.2 使用頻率

   中code

2. 簡單工廠模式結構

2.1 結構圖

2.2 參與者

  簡單工廠模式參與者:對象

  ◊ Product:抽象產品類,將具體產品類公共的代碼進行抽象和提取後封裝在一個抽象產品類中。blog

  ◊ ConcreteProduct:具體產品類,將須要建立的各類不一樣產品對象的相關代碼封裝到具體產品類中。繼承

  ◊ Factory:工廠類,提供一個工廠類用於建立各類產品,在工廠類中提供一個建立產品的工廠方法,該方法能夠根據所傳入參數的不一樣建立不一樣的具體產品對象。接口

  ◊ Client:客戶端類,只需調用工廠類的工廠方法並傳入相應的參數便可獲得一個產品對象。

3. 簡單工廠模式結構實現

3.1 Product類抽象實現

  Product.cs

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

namespace DesignPatterns.SimpleFactoryPattern.Structural
{
    public abstract class Product
    {
    }
}

  ConcreteProduct.cs

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

namespace DesignPatterns.SimpleFactoryPattern.Structural
{
    public class ConcreteProduct : Product
    {
    }
}

  Factory.cs

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

namespace DesignPatterns.SimpleFactoryPattern.Structural
{
    public class Factory
    {
        /// <summary>
        /// 靜態方法建立Product實例
        /// </summary>
        public static Product CreateProduct()
        {
            return new ConcreteProduct();
        }
    }
}

  Program.cs

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

using DesignPatterns.SimpleFactoryPattern.Structural;

namespace DesignPatterns.SimpleFactoryPattern
{
    class Program
    {
        static void Main(string[] args)
        {
            Product product = Factory.CreateProduct();
            Console.WriteLine("Created {0}", product.GetType().Name);
        }
    }
}

  運行結果:

Created ConcreteProduct
請按任意鍵繼續. . .

3.2 Product接口類實現

  IProduct.cs

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

namespace DesignPatterns.SimpleFactoryPattern.StructuralInterfaceImplementation
{
    public interface IProduct
    {
        void Display();
    }
}

  Product.cs

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

namespace DesignPatterns.SimpleFactoryPattern.StructuralInterfaceImplementation
{
    public class Product : IProduct
    {
        public void Display()
        {
            Console.WriteLine("DesignPatterns.SimpleFactoryPattern.Structural.Product");
        }
    }
}

  Factory.cs

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

using System.Reflection;

namespace DesignPatterns.SimpleFactoryPattern.StructuralInterfaceImplementation
{
    public class Factory
    {
        /// <summary>
        /// Factory返回IProduct的靜態方法
        /// </summary>
        /// <returns></returns>
        public static IProduct Create()
        {
            // 使用new直接建立接口的具體類
            //return new DesignPatterns.SimpleFactoryPattern.StructuralInterfaceImplementation.Product();

            // 經過映射建立接口的具體類
            return (IProduct)Assembly.Load("DesignPatterns.SimpleFactoryPattern").CreateInstance("DesignPatterns.SimpleFactoryPattern.StructuralInterfaceImplementation.Product");
        }
    }
}

  Program.cs

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

using DesignPatterns.SimpleFactoryPattern.StructuralInterfaceImplementation;

namespace DesignPatterns.SimpleFactoryPattern
{
    class Program
    {
        static void Main(string[] args)
        {
            IProduct product = Factory.Create();
            product.Display();
        }
    }
}

4. 簡單工廠模式實踐應用

4.1 實踐應用——運算操做

  Operation.cs

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

namespace DesignPatterns.SimpleFactoryPattern.Practical
{
    /// <summary>
    /// 運算類
    /// </summary>
    public abstract class Operation
    {
        public double NumberA { get; set; }
        public double NumberB { get; set; }

        public virtual double GetResult()
        {
            const double result = 0;
            return result;
        }
    }
}
View Code

  Plus.cs

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

namespace DesignPatterns.SimpleFactoryPattern.Practical
{
    /// <summary>
    /// 加法運算
    /// </summary>
    public class Plus : Operation
    {
        public override double GetResult()
        {
            return NumberA + NumberB;
        }
    }
}
View Code

  Minus.cs

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

namespace DesignPatterns.SimpleFactoryPattern.Practical
{
    /// <summary>
    /// 減法運算
    /// </summary>
    public class Minus : Operation
    {
        public override double GetResult()
        {
            return NumberA - NumberB;
        }
    }
}
View Code

  Multiply.cs

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

namespace DesignPatterns.SimpleFactoryPattern.Practical
{
    public class Multiply : Operation
    {
        public override double GetResult()
        {
            return NumberA * NumberB;
        }
    }
}
View Code

  Divide.cs

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

namespace DesignPatterns.SimpleFactoryPattern.Practical
{
    public class Divide :Operation
    {
        public override double GetResult()
        {
            return NumberA / NumberB;
        }
    }
}
View Code

  OperationFactory.cs

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

namespace DesignPatterns.SimpleFactoryPattern.Practical
{
    public class OperationFactory
    {
        public static Operation CreateOperate(string operate)
        {
            Operation operation = null;

            switch (operate)
            {
                case "+":
                    operation = new Plus();
                    break;
                case "-":
                    operation = new Minus();
                    break;
                case "*":
                    operation = new Multiply();
                    break;
                case "/":
                    operation = new Divide();
                    break;
            }

            return operation;
        }
    }
}
View Code

  Program.cs

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

using DesignPatterns.SimpleFactoryPattern.Practical;

namespace DesignPatterns.SimpleFactoryPattern
{
    class Program
    {
        static void Main(string[] args)
        {
            Operation operateion = OperationFactory.CreateOperate("+");
            operateion.NumberA = 10;
            operateion.NumberB = 5;

            Console.WriteLine(operateion.GetResult());
        }
    }
}
View Code

4.2 實踐應用——銀行支付接口

  IPayment.cs

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

namespace DesignPatterns.SimpleFactoryPattern.Practical
{
    public interface IPayment
    {
        bool Payfor(decimal money);
    }
}
View Code

  ABCPayment.cs

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

namespace DesignPatterns.SimpleFactoryPattern.Practical
{
    public class ABCPayment : IPayment
    {
        public bool Payfor(decimal money)
        {
            // 調用中國農業銀行支付接口進行支付
            return true;
        }
    }
}
View Code

  ICBCPayment.cs

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

namespace DesignPatterns.SimpleFactoryPattern.Practical
{
    public class ICBCPayment : IPayment
    {
        public bool Payfor(decimal money)
        {
            // 調用中國工商銀行支付接口進行支付
            return true;
        }
    }
}
View Code

  PaymentFactory.cs

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

namespace DesignPatterns.SimpleFactoryPattern.Practical
{
   public class PaymentFactory
    {
       public static IPayment CreatePayment(string bank)
       {
           IPayment payment = null;
           switch (bank)
           { 
               case "ABC":
                   payment = new ABCPayment();
                   break;
               case "ICBC":
                   payment = new ICBCPayment();
                   break;
           }

           return payment;
       }
    }
}
View Code

  OrderService.cs

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

namespace DesignPatterns.SimpleFactoryPattern.Practical
{
   public class OrderService
    {
       public bool CreateOrder(string bank)
       {
           decimal money=100m;
           var payment = PaymentFactory.CreatePayment(bank);

           return payment.Payfor(money);
       }
    }
}
View Code

  在OrderService類中,不依賴具體的支付類,只經過PaymentFactory來獲取真正的支付類。

5. 簡單工廠模式應用分析

5.1 簡單工廠模式優勢

  ◊ 實現建立和使用分離;

  ◊ Client無需知道所建立的ConcreteProduct類名,只須要知道ConcreteProduct所對應的參數。

5.2 簡單工廠模式缺點

  ◊ Factory類集中全部ConcreteProduct的建立邏輯,職責太重。一旦須要添加新的ConcreteProduct,則須要修改Factory邏輯。這樣違背了OCP(開放-關閉原則)

  ◊ 因爲使用了static方法,形成Factory沒法造成基於繼承的結構。

相關文章
相關標籤/搜索