在下面的場景中,需要根據某些條件邏輯對對象進行類型化,工廠方法模式是否有助於避免客戶端代碼因數量而變得混亂的if/elseif條件(如果由於邏輯的不同變化而需要創建越來越多的產品,這也會成爲維護的噩夢)。工廠方法模式,以避免基於條件邏輯實例化對象
或者還有其他的設計模式可以拯救嗎?
public interface IProduct
{
void Method1();
}
public class ProductA : IProduct
{
void Method1()
{
}
}
public class ProductB : IProduct
{
void Method1()
{
}
}
public class ProductC : IProduct
{
void Method1()
{
}
}
public class Client
{
public void Test()
{
int count = 5;
IProduct product;
if (count < 10)
{
product = new ProductA();
}
else if (count == 10)
{
product = new ProductB();
}
else if (count > 10)
{
product = new ProductC();
}
product.Method1();
}
}