抽象工厂模式
抽象工厂模式为创建一系列相关或依赖对象提供了接口,而无需指定它们的具体类。
AbstractFactory
为创建抽象产品的操作声明一个接口
ConcreteFactory
实现创建具体产品对象的操作
AbstractProduct
声明产品对象类型的接口
Product
AbstractProduct接口的实现,由相应的工厂创建的产品对象
Client
使用AbstractFactory和AbstractProduct类声明的接口
示例代码
/// <summary>
/// AbstractFactory
/// </summary>
public abstract class MobilePhoneFactory
{
public abstract SmartPhone CreateSmartPhone();
public abstract NormalPhone CreateNormalPhone();
}
/// <summary>
/// AbstractProduct 1
/// </summary>
public class SmartPhone
{
public virtual void ShowDetails() { }
}
/// <summary>
/// AbstractProduct 2
/// </summary>
public class NormalPhone
{
public virtual void ShowDetails() { }
}
/// <summary>
/// ConcreteFactory 1
/// </summary>
public class HuaweiFactory : MobilePhoneFactory
{
public override NormalPhone CreateNormalPhone()
{
return new HuaweiA616();
}
public override SmartPhone CreateSmartPhone()
{
return new HuaweiP50();
}
}
/// <summary>
/// ConcreteFactory 2
/// </summary>
public class NokiaFactory : MobilePhoneFactory
{
public override NormalPhone CreateNormalPhone()
{
return new Nokia1280();
}
public override SmartPhone CreateSmartPhone()
{
return new Nokia1020();
}
}
/// <summary>
/// Product 1
/// </summary>
internal class HuaweiA616 : NormalPhone
{
public override void ShowDetails()
{
System.Console.WriteLine("Huawei A616,体积为72.5×37.5×20.6mm,重56g,支持小灵通...");
}
}
/// <summary>
/// Product 2
/// </summary>
internal class HuaweiP50 : SmartPhone
{
public override void ShowDetails()
{
System.Console.WriteLine("Huawei P50,长度 156.5mm 宽度 73.8mm 厚度 7.92mm,5000 万像素原色摄像头(彩色,f/1.8 光圈),八核,1 x Cortex-X1@2.84 GHz + 3 x Cortex-A78@2.42 GHz + 4 x Cortex-A55@1.8 GHz...");
}
}
/// <summary>
/// Product 3
/// </summary>
internal class Nokia1020 : SmartPhone
{
public override void ShowDetails()
{
System.Console.WriteLine("Nokia 1020,130.4mm×71.4mm×10.4mm,158g,操作系统采用 Windows Phone 8.1,4,100 万像素 PureView 摄像头...");
}
}
/// <summary>
/// Product 4
/// </summary>
internal class Nokia1280 : NormalPhone
{
public override void ShowDetails()
{
System.Console.WriteLine("Nokia 1280,主屏分辨率 96x68像素,尺寸 107.2x45.1x15.3mm...");
}
}
/// <summary>
/// Client
/// </summary>
public class MobileDealer
{
private NormalPhone normalPhone;
private SmartPhone smartPhone;
public MobileDealer(MobilePhoneFactory factory)
{
normalPhone = factory.CreateNormalPhone();
smartPhone = factory.CreateSmartPhone();
}
public void Reserve()
{
normalPhone.ShowDetails();
smartPhone.ShowDetails();
}
}
//---------------------------------------
static void Main(string[] args)
{
MobilePhoneFactory factory = new HuaweiFactory();
MobileDealer dealer = new MobileDealer(factory);
dealer.Reserve();
factory = new NokiaFactory();
dealer = new MobileDealer(factory);
dealer.Reserve();
}