定义:可以理解为负责生产对象的一个类。
优点:
a.解决了客户端直接依赖于具体对象的问题,客户端可以消除直接创建对象的责任,而仅仅是消费产品。实现了对责任的分割;
b.起到了代码复用的作用。
缺点:
a.工厂类中集中了所有产品的创建逻辑,一旦不能正常工作,整个系统都会受到影响;
b.系统扩展困难,一旦添加新的产品就不得不修改工厂逻辑,这样就会造成工厂逻辑过于复杂。
适用场景:
a.当工厂类创建的类比较少时可以考虑使用简单工厂模式;
b.客户如果只知道传入工厂类的参数,对于如何创建对象的逻辑不关心时可以考虑使用简单工厂模式。
关键点:一个抽象基类、多个产品子类、一个工厂方法,客户端通过传递给工厂方法参数来获取具体的产品进行消费。
示例:
public abstract class Transportation
{
public abstract string GetType();
}
#region 具体操作,子类。
//坐地铁上班
public class ByMetro : Transportation
{
public override string GetType()
{
return "坐地铁";
}
}
//骑OFO上班
public class ByOfo : Transportation
{
public override string GetType()
{
return "骑OFO";
}
}
//徒步上班
public class OnFoot : Transportation
{
public override string GetType()
{
return "开11号";
}
}
#endregion
//工厂类
public class TransportationFactory
{
public static Transportation CreateTransportation(string transType)
{
Transportation transportation = null;
if (transType.Equals("地铁"))
{
transportation = new ByMetro();
}
else if (transType.Equals("OFO"))
{
transportation = new ByOfo();
}
else if (transType.Equals("走路"))
{
transportation = new OnFoot();
}
return transportation;
}
}
调用:
Console.WriteLine("【简单工厂模式】");
Console.WriteLine();
Console.WriteLine("出行方式:");
Console.WriteLine();
Transportation tf1 = TransportationFactory.CreateTransportation("地铁");
Console.WriteLine(tf1.GetType());
Console.WriteLine();
Transportation tf2 = TransportationFactory.CreateTransportation("OFO");
Console.WriteLine(tf2.GetType());
Console.WriteLine();
Transportation tf3 = TransportationFactory.CreateTransportation("走路");
Console.WriteLine(tf3.GetType());
Console.ReadLine();
输出: