How is Factory Method related to the open/closed principle (OCP)?
Factory Method directly supports the open/closed principle (OCP) because it lets you extend the system's behavior without changing existing code.
1. The essence of OCP
The principle states:
Classes should be open for extension but closed for modification. In other words, when adding new behavior we should add code, not change what already exists.
2. How it works in Factory Method
Instead of hard-coding in the client code which object to create with new, we use the abstract method createProduct().
If a new product type appears, we simply:
- create a new subclass,
- override the factory method in it.
abstract class Creator {
abstract Product createProduct();
}
class ConcreteCreatorA extends Creator {
Product createProduct() { return new ProductA(); }
}
class ConcreteCreatorB extends Creator {
Product createProduct() { return new ProductB(); }
}At the same time, the base code that uses createProduct() stays unchanged.
3. Example
If you add a new type of transport (for example, Plane), you do not need to change the Logistics class - it is enough to create AirLogistics and override createTransport().
4. Conclusion
Factory Method lets you add new object types without changing the existing logic, which makes the system flexible and extensible, fully in line with the OCP.
Short Answer
Interview readyA concise answer to help you respond confidently on this topic during an interview.