工厂方法模式以避免基于条件逻辑的对象实例化
在如下场景中,需要根据某些条件逻辑来实例化对象,工厂方法模式是否可以帮助避免客户端代码由于 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();
}
}
In a scenario like below where an object needs to be intantiated based on some conditional logic, can the factory method pattern help to avoid client code getting cluttered due to number of if/elseif conditions (which would also be a maintenance nightmare if more and more products needs to get created due to different variations of logics).
Or else is there a any other design pattern that could come to rescue?
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();
}
}
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
看起来工厂模式正是您想要的:
然后无论您的客户端代码需要一个实例,它都可以去
It looks like the factory pattern is exactly what you want:
Then wherever your client code needs an instance it can just go
我不相信Carver先生的解决方案严格遵循GOF设计模式书中描述的工厂模式的结构。然而,它是一种非常常见的编程习惯(简单工厂),并且可能是这种设计的好方法。
工厂模式要求从创建者派生具体创建者。通常,创建者将产品的创建委托给具体创建者。当将来可能添加新工厂时,这非常有用。例如,想象一下,如果您创建了一个新工厂,可以使用较少的资源(计数用作“资源”的代理)来制造特定产品。
I don't believe Mr. Carver's solution strictly follows the structure of the Factory Pattern described in the GOF Design Pattern book . However, it is a very common programming idiom (Simple Factory) and likely a good approach for this design.
The Factory Pattern calls for the Concrete Creator to be derived from a Creator. Typically, the Creator delegates the creation of the product to the Concrete Creator. This is useful when a new factory might be added in the future. For example, imagine if you created a new factory that could manufacture a the specific products with less resources (count is used as a proxy for "resource").