7

As I understand Factory Method is Simple Factory and Factory Object is Abstract Factory? And:

-Factory Method (Simple Factory):

public class SimplePizzaFactory {
    public static final int CHEESE = 1;
    public static final int PEPPERONI = 2;
    public static final int VEGGIE = 3;

    public static Pizza createPizza(int type) {
        Pizza pizza = null;

        if (type == CHEESE) {
            pizza = new CheesePizza();
        } else if (type == PEPPERONI ) {
            pizza = new PepperoniPizza();
        } else if (type == VEGGIE ) {
            pizza = new VeggiePizza();
        }

        return pizza;
    }
}

Factory Object(Abstract Factory):

?

Am I right?

How much are there realizations of Factory patterns and what is their difference?

Dave Schweisguth
  • 36,475
  • 10
  • 98
  • 121
drifter
  • 683
  • 1
  • 11
  • 24
  • Just another thing, unless you're using some ancient version of Java, please use enum instead of ints to enumerate possible types of pizza. – Renato Feb 02 '12 at 19:14
  • +1, I found this ancient example.(Java that time had not enums yet.) – drifter Feb 02 '12 at 19:16

1 Answers1

6

No. A factory-method is a factory that does not require any state. A factory class is a class itself - it has state, and methods that alter that state. In the end you call the .create() method, and it uses its current state to create a new object of a different type.

Abstract factory is a different thing - there you have multiple factory implementations of the same abstract concept. The wikipedia example is about e GUIFactory - this is an abstract factory, which has two implementations: WinFactory and OSXFactory. The client code does not know which implementation it is using - it just knows the factory creates Button instances. Which make it possible to write the same code regardless of the OS.

Bozho
  • 588,226
  • 146
  • 1,060
  • 1,140
  • So there are 3 main types: - Factory - Abstract Factory - Factory method ? – drifter Feb 02 '12 at 19:02
  • yes, that's correct. The factory and factory method don't differ that much though. – Bozho Feb 02 '12 at 19:02
  • Your answer is clear. I understand what is difference between Factory and factory method, but which is better to use? and why? – grep Jun 19 '15 at 10:06
  • that's the point - there is no silver bullet :) Factory method is likely to be applicable in more situations, I think – Bozho Jun 29 '15 at 16:47