简单工厂模式优缺点:
模式的核心是工厂类,这个类负责产品的创建,而客户端可以免去产品创建的责任,这实现了责任的分割。但由于工厂类集中了所有产品创建逻辑的,如果不能正常工作的话会对系统造成很大的影响。如果增加新产品必须修改工厂角 {MOD}的源码。
以园丁种植水果为例讨论该模式的具体实现:
Fruit 水果接口,规定水果具有的一些共同特性
Apple 苹果类 派生自Fruit接口
Strawberry 草莓类 派生自Fruit接口
FruitGardener 园丁类 负责草莓与苹果的创建工作。
当Client要创建水果(苹果或草莓对象)的时候调用园丁类的factory方法创建:UML图如下:
代码如下:
Fruit.cs
namespace Simple_Factory
{
public interface Fruit
{
//生长
void grow();
//收获
void harvest();
//种植
void plant();
}
}
Apple.cs
namespace Simple_Factory
{
public class Apple:Fruit
{
public Apple()
{
}
#region Fruit 成员
public void grow()
{
Console.WriteLine ("Apple is growing.......");
}
public void harvest()
{
Console.WriteLine ("Apple is harvesting.......");
}
public void plant()
{
Console.WriteLine ("Apple is planting.......");
}
#endregion
}
}
Strawberry.cs
namespace Simple_Factory
{
public class Strawberry:Fruit
{
public Strawberry()
{
}
#region Fruit 成员
public void grow()
{
Console.WriteLine ("Strawberry is growing.......");
}
public void harvest()
{
Console.WriteLine ("Strawberry is harvesting.......");
}
public void plant()
{
Console.WriteLine ("Strawberry is planting.......");
}
#endregion
}
}
FruitGardener.cs
namespace Simple_Factory
{
public class FruitGardener
{
//静态工厂方法
public static Fruit factory(string which)
{
if(which.Equals ("Apple"))
{
return new Apple();
}
else if(which.Equals ("Strawberry"))
{
return new Strawberry ();
}
else
{
return null;
}
}
}
}
Client.cs
using System;
namespace Simple_Factory
{
class Client
{
[STAThread]
static void Main(string[] args)
{
Fruit aFruit=FruitGardener.factory ("Apple");//creat apple
aFruit.grow ();
aFruit.harvest ();
aFruit.plant();
aFruit=FruitGardener.factory ("Strawberry");//creat strawberry
aFruit.grow ();
aFruit.harvest ();
aFruit.plant();
}
}
}
输出如下:
Apple is growing.......
Apple is harvesting.......
Apple is planting.......
Strawberry is growing.......
Strawberry is harvesting.......
Strawberry is planting.......