原文鏈接:http://www.c-sharpcorner.com/UploadFile/19b1bd/design-patterns-simplified-part3-factory/ Design Patterns Simplified - Part 3 (Simple Factory)【設計模 ...
原文鏈接:http://www.c-sharpcorner.com/UploadFile/19b1bd/design-patterns-simplified-part3-factory/
Design Patterns Simplified - Part 3 (Simple Factory)【設計模式簡述--第三部分(簡單工廠)】
This article explains why and how to use the Simple Factory Design Pattern in software development. 這篇文章解釋了在軟體開發中為什麼使用,以及怎麼使用簡單工廠模式。I am here to continue the discussion of Design Patterns. Today we will explain another creational design pattern called Simple Factory.
我在這繼續來討論設計模式。今天我將會解釋另一個創造性的設計模式,也就是簡單工廠模式。
In case you have not had a look at our previous articles, go through the following link:
假設你沒有看我之前的文章,請先回去看,下麵是鏈接:
Before talking about its implementation let's begin with some fundamental questions as in the following.
在討論如何實現簡單工廠模式之前,先看下下麵一些基本的問題:
Purpose of the Factory pattern【工廠模式的目的】
I can think of two main objectives of using the Factory pattern. One is to achieve loose coupling between the client and business layer, another is to keep all the code for all the object instantiation logic in one place.
我能想到使用工廠模式的兩個主要的目的。一個是在客戶端和業務層之間達到松耦合,另外一個是確保所有對象的實例化的邏輯代碼都在一個位置。
Purpose of loose coupling【松耦合的目的】
In modern software development where changes in existing systems are frequent and software design is expected to be scalable, not having a loosely-coupled design can create many problems.
在現代軟體開發的過程中,需求的變更是很頻繁的,所以軟體的設計應該是要可擴展性好的,沒有一個松耦合的設計,可能會有很多問題。
For example, in an application with a 3-layer architecture, if object creation logic is at the client side, for any new addition of concrete classes, the developer needs to modify not just the business but the client layer as well. Think about the maintainability and added testing effort.
例如,在一個簡單三層框架的項目中,如果對象的創建是在客戶端,那麼任何新添加的具體的實體類,開發者,不僅需要去修改業務層還有客戶端層。為了考慮可維護性,還需要添加測試的工作。
How about if the client is only aware of the high-level contracts and not about its concreate implementation?
如果客戶端只需要關心和高一層次的關係,而不用關心具體的實現呢?
Yes, you got it right! The client just must pass the type of the object it needs and it will get it using the Factory Pattern.
Enough theory. Now let's talk about implementation.
是的,你是對的!客戶端僅僅只需要傳遞對象需要的類型,剩下的就交給工廠模式去做。理論已經足夠了,現在我們來討論一下,如何實現簡單工廠模式吧。
How to use the Simple Factory Pattern【怎麼樣來使用簡單工廠模式】
Let's try to understand using a simple example.
Assume the client wants to know the on-road price of various brands of cars and have an interface as in the following.
我們使用一個簡單的例子,來理解簡單工廠模式吧。假設客戶想要知道路上各種品牌汽車的價格,提供了下麵一個這樣的介面。
我們創建一個控制台程式,來學習簡單工廠模式:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace ConsoleApplication1
{
public interface ICar
{
/// <summary>
/// 獲取汽車價格
/// </summary>
/// <param name="model"></param>
/// <returns></returns>
string GetOnRoadPrice(string model);
}
}
We need to create a Factory class now that will sit between the client and business layers and it will provide the required object to the client based on the car brand passed.
我們現在需要去創建一個工廠類,這個工廠類位於客戶端和業務層之間,並基於傳遞的汽車品牌,提供客戶端需要的對象。
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace ConsoleApplication1
{
public class CarFactory
{
/// <summary>
/// 獲取汽車對象
/// </summary>
/// <param name="carBrand">汽車品牌</param>
/// <returns></returns>
public static ICar GetCar(string carBrand)
{
if (carBrand.ToLowerInvariant() == "baoma")
{
return new BaoMa();
}
else if (carBrand.ToLowerInvariant() == "benchi")
{
return new BenChi();
}
else if (carBrand.ToLowerInvariant() == "aodi")
{
return new AoDi();
}
else
{
return null;
}
}
}
}
And here goes the concreate business classes.
這裡接著創建具體的實體類。
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace ConsoleApplication1
{
class AoDi:ICar
{
public string GetOnRoadPrice(string model)
{
if (model.ToLowerInvariant() == "aodi")
{
return "300w 人民幣";
}
else
{
return "你輸入的汽車品牌找不到,請重新輸入!!!";
}
}
}
}
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace ConsoleApplication1
{
class BaoMa:ICar
{
public string GetOnRoadPrice(string model)
{
if (model.ToLowerInvariant() == "baoma")
{
return "200w 人民幣";
}
else
{
return "你輸入的汽車品牌找不到,請重新輸入!!!";
}
}
}
}
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace ConsoleApplication1
{
class BenChi:ICar
{
public string GetOnRoadPrice(string model)
{
if (model.ToLowerInvariant() == "glc")
{
return "550w 人民幣";
}
else
{
return "你輸入的汽車品牌找不到,請重新輸入!!!";
}
}
}
}
Now let's see how the client can use the setup we have created so far.
現在,我們看看客戶端怎麼使用我們目前為止創建的對象。
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace ConsoleApplication1
{
class Program
{
static void Main(string[] args)
{
//設置控制台標題欄中顯示的標題
Console.Title = "簡單工廠模式Demo學習";
ICar car = null;
string model = null;
//賓士車測試
car= CarFactory.GetCar("BenChi");
model = "glc";
Console.WriteLine("賓士系列{0}的汽車,售價為{1}",model,car.GetOnRoadPrice(model));
Console.ReadKey();
}
}
}
And here goes the class diagram. 這是類圖:
As you can see in the preceding code, the client is getting the required object by just passing the car brand. And then it calls the GetOnRoadPrice method to get the On-road price by passing model name. So just to summarize, using simple factory, we achieved the following. 上面的代碼中你可以看到,客戶端獲取需要的對象,僅僅通過傳遞汽車的品牌就可以了。然後傳遞model name調用GetOnRoadPrice 方法來獲取價格。所以總結一下,使用簡單工廠模式,我們達到了下麵的目的。
- Loose coupling between client and business layers.【客戶端和業務層之間的松耦合。】
- Placed object creation logic at common place.【把對象的創建邏輯,放在了一個公共的地方。】
- Abstracted concreate classes (Maruti, Hyundai) from client.【客戶端的類抽象化】
I hope you have liked this article. I look forward to your comments/suggestions.
我希望你喜歡這篇文章,期待你的評論和建議。