我有一个涉及网上商店的不同产品的项目。据我了解,如果您有多个从一个基类继承的类,那么工厂设计模式就是正确的选择。我只有在决定将逻辑用于实际决定使用哪个工厂的逻辑上时才有困难。
我已经为各种产品创建了类和工厂类。
public class Product
{
public int ID { get; protected set; }
public string Name { get; set; }
public ProductType Type { get; private set; }
public Product(int id)
{
ID = id;
Populate();
}
public virtual void CompleteOrder()
{
//SendMailToSupplier();
}
private void Populate()
{
//database stuff including setting the type
}
}
public class DigitalProduct : Product
{
public DigitalAsset ProductAsset { get; private set; }
public DigitalProduct(int id, DigitalAsset asset) : base(id)
{
ProductAsset = asset;
}
public override void CompleteOrder()
{
base.CompleteOrder();
//SendAssetToUser();
}
}
public class PrintProduct : Product
{
public PrintInformation Information { get; private set; }
public PrintProduct(int id, PrintInformation information) : base(id)
{
Information = information;
}
public override void CompleteOrder()
{
base.CompleteOrder();
//PreparePrintingFlle();
}
}
public abstract class ProductFactory
{
public abstract Product CreateProduct(int id);
}
public class GenericProductFactory : ProductFactory
{
public override Product CreateProduct(int id)
{
return new Product(id);
}
}
public class DigitalProductFactory : ProductFactory
{
public override Product CreateProduct(int id)
{
DigitalAsset asset = GetDigitalAsset(id);
return new DigitalProduct(id, asset);
}
private DigitalAsset GetDigitalAsset(int id)
{
DigitalAsset asset = new DigitalAsset();
//IO stuff
return asset;
}
}
public class PrintProductProductFactory : ProductFactory
{
public override Product CreateProduct(int id)
{
PrintInformation information = GetPrintInformation(id);
return new PrintProduct(id,information);
}
private PrintInformation GetPrintInformation(int id)
{
PrintInformation information = new PrintInformation();
//database stuff
return information;
}
}
现在完成订单后,将触发事件。
public void OrderCompleted(int orderId, List<int> productIds);
因此,这里有一个要创建产品对象的int列表,因此我可以将CompleteOrder
在它们各自的功能上。问题是要知道产品的类型,我需要从填充函数中填充的数据库中获取产品类型。
我可以做的是在ProductFactory中创建一个函数public ProductFactory GetFactory(int id)
。但是那时工厂是不能成为抽象类的。
另一个选择是在产品类中创建函数public static Product GetProduct(int id)
。然后哪个首先找出要使用的工厂并退回所创建的产品。
但是,这两个选项都很奇怪。我想念什么吗?还是其中一种实际的方法?
欢呼声。
public class ProductFactory
{
public Product GetProductById(int id)
{
var dbProduct = FetchFromDb(id);
switch(dbProduct.Type)
{
case "Print"
return CreatePrintProduct(dbProduct);
case "Digital"
return CreateDigitalProduct(dbProduct);
}
}
//You might also want a batch function to avoid calling the database for each product.
public IEnumerable<Product> GetProductByIds(IEnumerable<int> ids)
{
var dbProducts = FetchFromDb(ids);
...
}
}