标签:OLE key 价格 .com cad inf 分享 工厂模式 public
工厂模式,对象创建型模式的一种。顾名思义,就是一座用来生产某类产品的工厂,当我需要一个产品时,只需要向工厂下达订单即可,而不需要关心这个产品的生产过程。
所谓工厂,就是将派生自同一接口的对象(某类产品)的实例化(生产)过程封装到一个类(工厂)中,统一由这个类进行实例化,而不暴露这个对象的实例化过程。
为方便理解,举一个简单的例子。
我们去4S店看车时,会有销售人员给我们介绍各种车型。销售人员就是一个工厂,而汽车就是相应的产品。所以我们需要一个接口ICar(表示汽车这个品类)、实现这个接口的实体类(具体的汽车型号)和一个工厂类(销售人员)。
public interface ICar
{
string ShowPrice();
}public class Cadillac_XTS : ICar
{
public string ShowPrice()
{
return "30万";
}
}
public class Cadillac_SRX : ICar
{
public string ShowPrice()
{
return "40万";
}
}
public class Cadillac_XT5 : ICar
{
public string ShowPrice()
{
return "35万";
}
}public class CarShopFactory
{
public ICar GetCar(string model)
{
if (string.IsNullOrWhiteSpace(model))
{
return null;
}
if(model == "Cadillac_XTS")
{
return new Cadillac_XTS();
}
else if (model == "Cadillac_SRX")
{
return new Cadillac_SRX();
}
else if (model == "Cadillac_XT5")
{
return new Cadillac_XT5();
}
else
{
return null;
}
}
}
public static void Main(string[] args)
{
//创建工厂
CarShopFactory factory = new CarShopFactory();
//通过工厂获取相应对象实体
ICar xts = factory.GetCar("Cadillac_XTS");
ICar srx = factory.GetCar("Cadillac_SRX");
ICar xt5 = factory.GetCar("Cadillac_XT5");
//调用实体ShowPrice函数
Console.WriteLine($"XTS的价格是:{xts.ShowPrice()}");
Console.WriteLine($"SRX的价格是:{srx.ShowPrice()}");
Console.WriteLine($"XT5的价格是:{xt5.ShowPrice()}");
Console.ReadKey();
}
学习记录 - 设计模式[1]:工厂模式 (Factory Pattern)
标签:OLE key 价格 .com cad inf 分享 工厂模式 public
原文地址:https://www.cnblogs.com/wxingchen/p/9655360.html