参数传递给工厂模式

时间:2016-01-29 18:18:41

标签: parameters factory

我有很多优化模型,我有一个接口。

public interface IOptModel
{
    public void Optimize();
}

然后,我有一个工厂类,它创建了不同的优化模型。

public class FactoryOptModel
{
    private Dictionary<string, OptModel> models = new Dictionary<string, OptModel>();

    public OptModel getOptModel(string spec)
    {
        foreach(OptModel model in this.models)
            if(spec == "some name")
            {
                return model_map[spec];
            }
    }
}

我的问题是OptModel需要两个参数才能正常运行。一个是Problem对象,另一个是Config对象。随着更多模型的开发,我预计未来配置对象可能会发生变化。适合这个的设计是什么?谢谢!

1 个答案:

答案 0 :(得分:0)

OptModel接口:

public interface OptModel {

    void optimize(String config, String Problem);
}

工厂类:

    public class FactoryOptModel {
    public OptModel getOptModel(String spec) {
        if (spec == "Super Optimizer") {
            return new SuperOpt("Super Config", "Super Problem");
        } else if (spec == "Fastest Optimizer") {
            return new FastestOpt("Fastest Config", "Slowest Problem");
        }
        else return null;
    }
}

超级优化器实施:

public class SuperOpt implements OptModel{
    String config;
    String problem;
    public SuperOpt(String config, String problem){
        this.config = config;
        this.problem = problem;
    }
    public void optimize(String config, String problem){
        System.out.println("Fastest Optimizer with " + config + "and Problem " + Problem);
    }
}

最快的优化器实施:

public class FastestOpt implements OptModel {
    String config;
    String problem;
    public FastestOpt(String config, String problem){
        this.config = config;
        this.problem = problem;
    }
    public void optimize(String config, String Problem){
        System.out.println("Fastest Optimizer with " + config + "and Problem " + Problem);
    }
}

最后,一个演示:

public class FactoryPatternDemo {
    public static void main(String args[]){
        FactoryOptModel fom = new FactoryOptModel();

        OptModel superOptimizer = fom.getOptModel("Super Optimizer");
        OptModel fastestOptimizer = fom.getOptModel("Fastest Optimizer");

        superOptimizer.optimize("Super Config", "Super Problem");
        fastestOptimizer.optimize("Fastest Config", "Slowest Problem");
    }
}
相关问题