使用工厂模式

Use Factory pattern

我尝试在这段代码中使用工厂模式。我有一个将三个参数作为输入的方法 我需要 return 一个创造经典迪士尼情节的工厂。我是否正确应用了给定的模式?以及如何 return 一个创造迪士尼经典情节的工厂?

public PlotFactory classicDisneyPlotFactory(Character hero, Character another, Character without) {
        if (hero.equals("A") && another.equals("B") && without.equals("C")){
           return  .....;
        } else if (hero.equals("D") && another.equals("E")&& without.equals("F")){
            return ....;
        }else if (hero.equals("G") && another.equals("H")&& without.equals("I")){
            return ....;
        }
        
    }

Factory的设计模式应该这样使用:

public static void main(String[] args) {
    DisneyPlotFactory dPlotFactory = new DisneyPlotFactory();
    APlot plot1 = dPlotFactory.getPlot("A", "B", "C");
    plot1.execute();
    BPlot plot2 = dPlotFactory.getPlot("G", "H", "I");
    plot2.execute();
}

你对 classicDisneyPlotFactory 所做的应该 return 一个 Plot 而不是 PlotFactory,像这样:

public class DisneyPlotFactory { 
    public DisneyPlot getPlot(Character hero, Character another, Character without) {
        if (hero.equals("A") && another.equals("B") && without.equals("C")){
           return new APlot();
        } else if (hero.equals("D") && another.equals("E")&& without.equals("F")) {
            return new BPlot();
        }else if (hero.equals("G") && another.equals("H")&& without.equals("I")) {
            return new CPlot();
        }
        
    }
}

您可以每隔 class 创建工厂,工厂应该公开方法以获取根据您的参数生成的 DisneyPlot