0

I try to use Factory pattern in this code. I have a method that take three arguments as input and I need to return a factory that creates a classic Disney plot. Do I apply the given pattern correctly? And how return a factory that creates a classic Disney plot?

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 ....;
        }
        
    }

1 Answers1

1

The design pattern of Factory should be used like this:

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();
}

What you did with classicDisneyPlotFactory should return a Plot and not a PlotFactory, like this:

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();
        }
        
    }
}

You can create the factory just every other class, the factory should expose the method to get the DisneyPlot generated from your parameters.

Simone Lungarella
  • 301
  • 1
  • 4
  • 15
  • Note this is not a pattern from the GoF book. Head First Design Patterns calls this a "Simple Factory". – jaco0646 Oct 12 '21 at 21:06
  • Oh thanks, could you answer with the correct Factory implementation? I would like to see the difference with the Simple Factory. – Simone Lungarella Oct 13 '21 at 07:11
  • 1
    One implementation is no more correct than the others. There are just many kinds of factories. The two from the GoF book are described thoroughly in [What are the differences between Abstract Factory and Factory Method design patterns?](https://stackoverflow.com/questions/5739611/what-are-the-differences-between-abstract-factory-and-factory-design-patterns) There are other factory patterns in other books, such as Simple Factory in HFDP. – jaco0646 Oct 13 '21 at 13:15