Description
This PR implements theFactory Method Design Pattern in Java, addressing issue#3367.
The Factory Method pattern allows subclasses to decide which class to instantiate, improvingcode flexibility,reusability, andmaintainability.
Issue
- Problem: The repository requested a working example of the Factory Method pattern to demonstrate how a class can delegate object creation to subclasses.
- There was no concrete implementation for theBlacksmith & Weapon example, which was described in the issue.
- Without this, learners and contributors could not see apractical Java implementation of the pattern.
How This PR Resolves the Issue
- Created the
Blacksmith interface with the factory methodmanufactureWeapon(WeaponType weaponType). - Implementedconcrete factories:
ElfBlacksmith.java — creates Elven weaponsOrcBlacksmith.java — creates Orcish weapons
- Created
Weapon.java andWeaponType.java to represent the product and its types - Added
Main.java todemonstrate usage, showing that each blacksmith produces the correct weapons dynamically - This implementation provides aworking, compilable, and testable example of the Factory Method pattern in Java
Key Highlights
- Subclasses decide the type of object to create
- Encapsulates object creation logic, improving maintainability
- Demonstratesreal-world analogy: Blacksmiths produce weapons according to their type
Files Added
FactoryMethodPattern/
├── Blacksmith.java
├── ElfBlacksmith.java
├── OrcBlacksmith.java
├── Weapon.java
├── WeaponType.java
└── Main.java
## Example OutputOrc Blacksmith manufactured: Orcish SpearOrc Blacksmith manufactured: Orcish AxeElf Blacksmith manufactured: Elven SpearElf Blacksmith manufactured: Elven Axe
Additional Notes
- Code follows Java best practices and is self-contained for easy testing
- Ready for inclusion undercreational design patterns
- Contributes toHacktoberfest 2025 — kindly label as
hacktoberfest-accepted
Closes
Closes issue#3367
Description
This PR implements theFactory Method Design Pattern in Java, addressing issue#3367.
The Factory Method pattern allows subclasses to decide which class to instantiate, improvingcode flexibility,reusability, andmaintainability.
Issue
How This PR Resolves the Issue
Blacksmithinterface with the factory methodmanufactureWeapon(WeaponType weaponType).ElfBlacksmith.java— creates Elven weaponsOrcBlacksmith.java— creates Orcish weaponsWeapon.javaandWeaponType.javato represent the product and its typesMain.javatodemonstrate usage, showing that each blacksmith produces the correct weapons dynamicallyKey Highlights
Files Added
FactoryMethodPattern/
├── Blacksmith.java
├── ElfBlacksmith.java
├── OrcBlacksmith.java
├── Weapon.java
├── WeaponType.java
└── Main.java
Additional Notes
hacktoberfest-acceptedCloses
Closes issue#3367