简单工厂模式通过一个额外的类管理有共同接口的一系列类的创建。通过这个方法我们可以分离类的实际使用与创建时的数据依赖。
简单工厂模式的角色有:工厂类、产品接口、具体产品
举个例子说我们要创建家水果店。
其中工厂类 FruitShop,产品接口 Fruit、具体产品 Apple、Stawberry、Watermelon
// fruit.cs
namespace SimpleFactory
{
//产品接口
public interface Fruit
{
string Name { get; }
decimal Price { get; }
}
// 具体产品
public class Apple : Fruit
{
private static string name = "apple";
public string Name
{
get { return name; }
}
private static decimal price = 5;
public decimal Price
{
get { return price; }
}
}
//具体产品
public class Strawberry : Fruit
{
private static string name = "strawberry";
public string Name
{
get { return name; }
}
private static decimal price = 10;
public decimal Price
{
get { return price; }
}
}
//具体产品
public class Watermelon : Fruit
{
private static string name = "watermelon";
public string Name
{
get { return name; }
}
private static decimal price = 3;
public decimal Price
{
get { return price; }
}
}
}
// fruitShop.cs
using System;
namespace SimpleFactory
{
//工厂类
public abstract class FruitShop
{
public enum FruitType
{
Apple, Watermelon, Strawberry
}
public static Fruit Sell(FruitType fruit)
{
switch (fruit)
{
case FruitType.Apple: return new Apple();
case FruitType.Strawberry: return new Strawberry();
case FruitType.Watermelon: return new Watermelon();
default: throw new FruitTypeExpetion();
}
}
}
class FruitTypeExpetion : Exception
{
public FruitTypeExpetion() : base("Wrong Fruit type") { }
}
}
然后在控制台测试:
using System;
namespace SimpleFactory
{
class Program
{
static void Main(string[] args)
{
Fruit goods = FruitShop.Sell(FruitShop.FruitType.Apple);
Console.WriteLine("Goods : {0}, cost : {1}", goods.Name, goods.Price);
goods = FruitShop.Sell(FruitShop.FruitType.Strawberry);
Console.WriteLine("Goods : {0}, cost : {1}", goods.Name, goods.Price);
goods = FruitShop.Sell(FruitShop.FruitType.Watermelon);
Console.WriteLine("Goods : {0}, cost : {1}", goods.Name, goods.Price);
Console.ReadKey();
}
}
}
结果如下:
我们在这个例子里,把工厂类 FruitShop 设为抽象类,把创建产品的方法 Sell 设为静态方法,这样一来,可以省去实例化工厂类的消耗。
在简单工厂模式里,如果增加新的具体产品,只需实现产品接口并修改工厂类即可。