-
-
Notifications
You must be signed in to change notification settings - Fork 27.1k
Open
Description
Introduction
In Java applications, object instantiation for different types is often handled through separate factory classes. While this approach works, it can become verbose and hard to maintain — especially when the set of object types is known and fixed.
To improve clarity and maintainability, we propose adopting a cleaner pattern that combines factory logic and type mapping using enums.
Current Problem
- Object creation logic is scattered and not centralized.
- Requires additional boilerplate factory classes.
- No guarantee of singleton or controlled instance creation.
- Becomes harder to maintain as more types are added.
- Type safety is not enforced at compile-time in traditional factory implementations.
Proposed Solution
Adopt the Factory Enum Pattern — a temporary term to describe a technique that combines the Factory Pattern and Enum Singleton pattern.
In this approach:
- Each
enum
constant represents a known object type. - Each constant is associated with a corresponding singleton instance.
- Object creation is centralized and type-safe.
- Lazy-loaded singletons can be used via
InstanceHolder
.
Benefits:
- Cleaner and more readable instantiation logic.
- Eliminates the need for external factory classes.
- Guarantees singleton per type.
- Compile-time safety using enums.
- Naturally thread-safe due to enum and static initialization behavior.
Implementation Plan
- Define an enum containing constants for each object type.
- Each constant holds a reference to its singleton instance.
- Use a private static InstanceHolder class if lazy-loading is desired.
- Update client code to retrieve instances via the enum rather than constructors or factory methods.
Related Pull Request
This issue is related to PR: #3300
Apologies for submitting the pull request before filing this issue. This aims to provide additional context and rationale.
Metadata
Metadata
Assignees
Labels
No labels