I'm wondering if this is a valid practice of design patterns. I'm currently designing a code where it seems that there is a builder within the factory. I can smell something bad in my current design but I can't pinpoint it. The code looks something like this...
class Program
{
static void Main()
{
string productName = "productA";
IProduct product1 = new Factory().GetNewProduct(productName);
}
}
class Factory
{
internal IProduct GetNewProduct(string name)
{
IProduct product = null;
switch (name)
{
case "productA":
product = new ProductA();
break;
case "productB":
product = new ProductB();
break;
case "productC":
product = new ProductC();
break;
default:
throw new Exception("Invalid product type!");
}
//builder (sort of)
product.addPart1();
product.addPart2();
...
return product;
}
}
The problem with your approach is that there is no any flexibility in building the IProduct object, all objects are built in the same way, so if tomorrow some object need to be created in some other way. You will have to do heavy changes. What I would suggest is having a Factory method inside the Builder class as follows
class Builder {
IProduct product;
public Builder(String type) {
product = new Factory().getNewProduct(type);
}
public Builder addPart1() {
product.addPart1();
return this;
}
public Builder addPart2() {
product.addPart2();
return this;
}
public void build() {
return product;
}
private class Factory {
IProduct GetNewProduct(string name) {
IProduct product = null;
switch (name)
{
case "productA":
product = new ProductA();
break;
case "productB":
product = new ProductB();
break;
case "productC":
product = new ProductC();
break;
default:
throw new Exception("Invalid product type!");
}
return product;
}
}
}
class Program {
static void Main()
{
String productName = "productA";
IProduct product1 = new Builder(productName)
.addPart1()
.addPart2()
.build();
}
}
In this approach you can independently add more product types (in your Factory method) and build your object step by step with more parts :)