Petru Ciorba
Petru Ciorba

Reputation: 25

Use Factory pattern

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

Upvotes: 0

Views: 338

Answers (1)

Simone Lungarella
Simone Lungarella

Reputation: 333

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.

Upvotes: 1

Related Questions