我有一个现有的代码库,它使用静态工厂法设计来实例化某些对象类型:
public static Something createSomething(int x, int y, .....)
{
// creates a Something object
}我想扩展这个方法,允许它以一种不同的方式初始化某个对象,它基于新的参数,该参数将决定如何创建对象。
最简单(也是最不容易扩展的)方法是向工厂方法添加新参数。
这似乎不是做事情的正确方式:
是否有更好的方法来扩展工厂方法?
发布于 2013-09-03 20:20:03
创建一个新方法,并使用参数对象作为参数(这是一个命名模式吗?)。这样,您就不会更改以前的实现,并且可以接受任何新的实现(您可以更改参数对象而不影响当前对该方法的调用)。
更多的想法:是的,这样,你有两种方法,但如果你做的对,这不是一个问题:
public static Something createSomething(int x, int y, .....)
{
/// 1. Implementation
/// OR
/// 2. return createSomething(new SomethingDescription(parameters ...));
}
public static Something createSomething(SomethingDescription description)
{
/// 1. return createSomething(description.x, description.y, ...);
/// OR
/// 2. Implementation
}但是,如果对象确实很复杂,并且可以通过多种方式构建,那么您应该像Sotirios Delimanolis所建议的那样,切换到Builder模式。
https://stackoverflow.com/questions/18600454
复制相似问题