实例说明:某穷工厂生产汽车零配件,只制作车窗和车门。
首先把零部件抽象成一个类Hardware.cs:

Code
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace SimpleFactory
{
public abstract class Hardware
{
public string hardwareName { get; set; }
public virtual string GetHardware()
{
return "";
}
}
}
具体产品(车窗和车门)继承自该类,车窗类CarWindows.cs

Code
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace SimpleFactory
{
class CarWindows:Hardware
{
public CarWindows(string name)
{
this.hardwareName = name;
}
public override string GetHardware()
{
return "this is : " + this.hardwareName;
}
}
}
车门类CarDoors.cs

Code
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace SimpleFactory
{
public class CarDoors:Hardware
{
public CarDoors(string name)
{
this.hardwareName = name;
}
public override string GetHardware()
{
return "this is : " + this.hardwareName;
}
}
}
简单工厂的核心类集中了所有的判断逻辑,决定返回什么对象,其中的主要方法一般声明成静态方法,所以又称静态工厂。
CarFactory.cs:

Code
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace SimpleFactory
{
public class CarDoors:Hardware
{
public CarDoors(string name)
{
this.hardwareName = name;
}
public override string GetHardware()
{
return "this is : " + this.hardwareName;
}
}
}
好了,现在可以在客户端测试了。

Code
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace SimpleFactory
{
class Program
{
static void Main(string[] args)
{
Hardware hardware = CarFactory.CreateHareware("doors");
Console.WriteLine(hardware.hardwareName);
Console.Read();
}
}
}
Tips:简单工厂的产品类一般为具有某些共同特征的类,种类较多时可抽象出多个抽象产品类。
简单工厂不大复杂,就这么简单写好了,以后再研究其他设计模式,希望能把23种设计模式写完。