Virtual Constructor
Define an interface for creating an object, but let subclasses decide which class to instantiate. Factory Method lets a class defer instantiation to subclasses.
Real-world example
Blacksmith manufactures weapons. Elves require Elvish weapons and orcs require Orcish weapons. Depending on the customer at hand the right type of blacksmith is summoned.
In plain words
It provides a way to delegate the instantiation logic to child classes.
Wikipedia says
In class-based programming, the factory method pattern is a creational pattern that uses factory methods to deal with the problem of creating objects without having to specify the exact class of the object that will be created. This is done by creating objects by calling a factory method — either specified in an interface and implemented by child classes, or implemented in a base class and optionally overridden by derived classes—rather than by calling a constructor.
Programmatic Example
Taking our blacksmith example above. First of all, we have a Blacksmith
interface and some
implementations for it:
1public interface Blacksmith {
2 Weapon manufactureWeapon(WeaponType weaponType);
3}
4
5public class ElfBlacksmith implements Blacksmith {
6 public Weapon manufactureWeapon(WeaponType weaponType) {
7 return ELFARSENAL.get(weaponType);
8 }
9}
10
11public class OrcBlacksmith implements Blacksmith {
12 public Weapon manufactureWeapon(WeaponType weaponType) {
13 return ORCARSENAL.get(weaponType);
14 }
15}
When the customers come, the correct type of blacksmith is summoned and requested weapons are manufactured:
1Blacksmith blacksmith = new OrcBlacksmith();
2Weapon weapon = blacksmith.manufactureWeapon(WeaponType.SPEAR);
3LOGGER.info("{} manufactured {}", blacksmith, weapon);
4weapon = blacksmith.manufactureWeapon(WeaponType.AXE);
5LOGGER.info("{} manufactured {}", blacksmith, weapon);
6
7blacksmith = new ElfBlacksmith();
8weapon = blacksmith.manufactureWeapon(WeaponType.SPEAR);
9LOGGER.info("{} manufactured {}", blacksmith, weapon);
10weapon = blacksmith.manufactureWeapon(WeaponType.AXE);
11LOGGER.info("{} manufactured {}", blacksmith, weapon);
Program output:
The orc blacksmith manufactured an orcish spear
The orc blacksmith manufactured an orcish axe
The elf blacksmith manufactured an elven spear
The elf blacksmith manufactured an elven axe
Use the Factory Method pattern when: