I know there are a lot of questions out there about differences of different factory patterns, but the answers are so different and confusing. The books that i read use uncl
Simple Factory - This isn't an official GoF pattern, infact I had no idea what you were talking about until I pulled out my Head First Design Pattern Book. Simple Factory is just a method that can return different hardcoded subtypes.
public Pizza createPizza(String type){
if(type.equals("cheese")){
return new CheesePizza();
}else if (type.equals("pepperoni")){
return new PepperoniPizza();
}
...
}
The problem with this code is you are stuck with only the hardcoded types. If you want to change how the method works, or what types are returned you have to modify code and recompile. Adding new types will be very difficult.
Factory Method - you do most of the work in a super class but put off deciding what sort of object you will be working with until runtime. Often the superclass needs to create a worker object of some default type but the superclass allows subclasses to specialize the worker. Factory Methods are usually used when an AbstractFactory is overkill but one downside is it forces you to use inheritance which has its own set of maintenance and design problems. This is very similar to SimpleFactory except you use inheritance instead of a discriminator to get different return types.
public void foo(){
Bar bar = createBar();
//do stuff with bar
}
//method is protected so subclass can override it to return something else
protected Bar createBar(){
return new DefaultBar();
}
AbstractFactory - Create Objects knowing only the interface they implement not the actual class. AbstractFactories make it easy for code to work in different systems because you don't need to know the concrete factory or concrete products that are used.
For example Collection.iterator() is an abstract factory of Iterator objects. Classes such as LinkedList or HashSet have their own implementations of iterator() (and therefore are Concrete Factories) that return different classes that implement the iterator interface (the concrete product)
Once you finish Head First Design Patterns I recommend Holub on Patterns the code is a little dated (pre-generics) but you really learn a lot about how multiple patterns interact with one another in non-trivial code samples. The book only has 2 code samples which each cover about 10 patterns and take 100+ pages each to explain step by step