Factory Method VS Factory Object [duplicate]
Asked Answered
Y

1

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?

Yoko answered 2/2, 2012 at 18:50 Comment(2)
Just another thing, unless you're using some ancient version of Java, please use enum instead of ints to enumerate possible types of pizza.Rossi
+1, I found this ancient example.(Java that time had not enums yet.)Yoko
J
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.

Jaal answered 2/2, 2012 at 18:58 Comment(4)
So there are 3 main types: - Factory - Abstract Factory - Factory method ?Yoko
yes, that's correct. The factory and factory method don't differ that much though.Jaal
Your answer is clear. I understand what is difference between Factory and factory method, but which is better to use? and why?Weapon
that's the point - there is no silver bullet :) Factory method is likely to be applicable in more situations, I thinkJaal

© 2022 - 2024 — McMap. All rights reserved.