The Factory Method Pattern is a creational design pattern that provides an interface for creating objects in a superclass but allows subclasses to alter the type of objects that will be created.
The Factory Method Pattern defines a method that subclasses must override to specify the type of object to create. This promotes loose coupling by reducing the dependency of client code on specific classes.
Key features:
- Encapsulation of Object Creation: The creation logic is moved to a factory method.
- Flexibility: Subclasses can determine what type of object to instantiate.
- Polymorphism: The client interacts with a common interface, not specific implementations.
- Customization: Allows subclasses to change the type of object created without modifying client code.
- Scalability: Makes it easy to introduce new types of objects without altering existing code.
- Consistency: Ensures all objects follow a consistent creation process.
The implementation of the Factory Method Pattern can be found in:
ObstacleFactory.java: Abstract factory for creating obstacles.PowerUpFactory.java: Abstract factory for creating power-ups.GoombaFactory.java,KoopaFactory.java: Concrete factories for obstacles.MushroomFactory.java,StarFactory.java: Concrete factories for power-ups.Game.java: Demonstrates the usage of the Factory Method Pattern.
To see the Factory Method Pattern in action, refer to the Game.java file.
- GUI Frameworks:
- A dialog class creates buttons using a factory method. Subclasses of the dialog can decide whether to create Windows buttons, macOS buttons, or other types.
- Data Parsers:
- A file reader factory can produce XML, JSON, or CSV parsers based on configuration.
classDiagram
class Factory {
+createProduct() Product
}
class Product {
}
class ConcreteFactory1 {
+createProduct() Product
}
class ConcreteFactory2 {
+createProduct() Product
}
class ConcreteProduct1 {
}
class ConcreteProduct2 {
}
Product <|-- ConcreteProduct2
Factory <|-- ConcreteFactory1
Factory <|-- ConcreteFactory2
ConcreteFactory1 --> ConcreteProduct1 : CREATES
ConcreteFactory2 --> ConcreteProduct2 : CREATES
Product <|-- ConcreteProduct1
Factory --> Product : HAS-A
Note
If the UML above is not rendering correctly, you can view the diagram from the factory-method_uml.png file.
- The Factory Method Pattern provides a way to encapsulate object creation.
- Use it when the client code should not depend on specific classes or object types.
- It promotes flexibility and scalability in your application.