I read the difference between factory
pattern and factory method
pattern.
Factory method pattern defers instantiation of an object to subclasses. Also it is a Factory Method because the children of “Creator” are responsible for implementing the “Create” method.
Where as a simple factory is called directly by the class which wants to create an object.
But for factory pattern also we can decouple the factory class by adding class registration through reflection and using a layer of subclasses for the objects to be created and keeping the object instantiation logic inside this subclasses.
I am not getting an example of the factory method pattern that conforms to the above definition of factory method pattern.
Can you please provide me a factory method example?
Suppose we want to produce fruits:
public interface Fruit {
public void plant();
public void grow();
}
// concrete fruit Apple
public class Apple implements Fruit {
@Override
public void plant() {
System.out.println("Apple is planted.");
}
@Override
public void grow() {
System.out.println("Apple is growing.");
}
}
// concrete fruit Banana
public class Banana implements Fruit {
@Override
public void plant() { ... }
@Override
public void grow() { ... }
}
In factory pattern, there is one factory class responsible for producing new instances. While the disadvantage is that if added one type of instance, have to change logic of the factory class.
Example:
// Factory class
public class FruitGarden {
public static Fruit createFruit(String fruitName) throws Exception {
if(fruitName.equals("Apple")) {
return new Apple();
} else if(fruitName.equals("Banana")) {
return new Banana();
} else {
System.out.printf("Sorry! %s not supported.\n", fruitName);
throw new Exception();
}
}
/* another way to create instance
public static Fruit createApple() {
return new Apple();
}
public static Fruit createBanana() {
return new Banana();
}
*/
}
In factory method pattern, there is an abstract factory representing the creation of new instances. Different type of instances are created by different concrete factories. All these concrete factories implement the abstract factory interface or extends abstract factory class. If added one new type, just add one concrete factory, so it has more expandability.
Example:
// abstract factory interface
public interface FruitGarden {
public Fruit createFruit();
}
// concrete factory which is responsible producing Apple
public class AppleGarden implements FruitGarden {
@Override
public Fruit createFruit() {
return new Apple();
}
}
// concrete factory which is responsible producing Banana
public class BananaGarden implements FruitGarden {
@Override
public Fruit createFruit() {
return new Banana();
}
}
Java's Collection.iterator()
is a factory method.
The concrete implementation of the collection determines what concrete iterator is returned by this method.