我有用於構建項目的構建器 - 導演實現。應該使用哪種模式來確定用於項目的構建器?
public void main(ItemKey itemKey) {
Director aDirector = new Director();
ItemBuilderFactory itemBuilderFactory = new ItemBuilderFactory();
var builder = itemBuilderFactory.GetBuilderFor(itemKey); //<--- How to do this?
aDirector.Construct(builder, itemKey);
Console.WriteLine(builder.Item.BusinessName);
Console.WriteLine(builder.Item.CustomerName);
Console.WriteLine(builder.Item.AdvancedName);
}
public class Director {
public void Contruct(IItemBuilder builder, ItemKey itemKey) {
builder.CreateItem();
builder.GetBusinessItemInformation(itemKey);
builder.GetCustomerItemInformation(itemKey);
builder.GetAdvancedItemInformation(itemKey);
}
}
public interface IItemBuilder {
Item Item { get; }
void GetBusinessItemInformation(ItemKey itemKey);
void GetCustomerItemInformation(ItemKey itemKey);
void GetAdvancedItemInformation(ItemKey itemKey);
bool CanBuild(ItemKey itemKey); // I don't like this and I think it violates SRP. Forces me to retrieve info about the item, then determine if the builder can build it, and return a flag indicating it.
void CreateItem();
}
public class ItemBuilderFactory {
private readonly List<IItemBuilder> _builders;
public ItemBuilderFactory(List<IItemBuilder> builders) {
_builders = builders;
}
public IItemBuilder GetBuilderFor(ItemKey itemKey) {
//What do I do here? Current impl:
return _builders.Single(builder => builder.CanBuild(itemKey)); //huge red flag, just a fancy if
}
}
public class ItemKey {
public int Upc {get;set;}
public string ItemCode {get;set;}
}
我儘量避免使用if語句,但是這似乎是我可能需要的時候。我還能怎樣「讓建造者能夠建造這個物品」?我曾想過創建某種映射類,但是這會嚴重增加查看代碼的認知開銷,並且可能有人會將我推向正確的方向。
對不起,我應該提供了一個itemkey的例子,請參閱已編輯的問題。 – 2014-11-10 23:04:52
雖然我仍然可以使用你的實現,但它只需要一個IDictionary –
2014-11-10 23:06:21
是的,也只是挑剔,但是你有意爲給定的鍵返回相同的構建器實例,那麼它應該被稱爲與Factory不同的東西。 – 2014-11-10 23:30:59