Skip to content

feat: add factory enum #3300

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Open
wants to merge 1 commit into
base: master
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
126 changes: 126 additions & 0 deletions factory-enum/README.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,126 @@
---
title: "Factory Enum Pattern in Java: Simplifying Object Access"
shortTitle: Factory Enum
description: "Learn the Factory Enum Pattern in Java using practical examples. Understand how to use enums to manage object instantiation in a clean, scalable, and singleton-safe way."
category: Creational
language: en
tag:
- Abstraction
- Enum Singleton
- Gang of Four
- Factory Pattern
- Object Instantiation
---

## Intent of Factory Enum Pattern

The **Factory Enum Pattern** is a creational pattern that leverages Java's `enum` type to manage object instantiation. It provides a centralized, type-safe, and singleton-friendly way to access various implementations of a common interface.

This pattern is ideal when the set of possible objects is known and fixed (e.g., file processors, coin types, document types).

## Real-World Analogy

> Imagine a toolbox where each tool has a fixed slot. You don’t create a new tool each time — you just access the correct one from the right compartment. Similarly, with Factory Enum, each `enum` constant maps to a specific object instance that can be reused or constructed once.

## Programmatic Example Using FileProcessor

In this example, we want to process different file types: Excel and PDF. Each processor implements the `FileProcessor` interface.

### FileProcessor Interface

```java
public interface FileProcessor {
String getDescription();
}
```
Implementations
```java
@NoArgsConstructor(access = AccessLevel.PRIVATE)
public class ExcelProcessor implements FileProcessor {

static final String DESCRIPTION = "This is an Excel processor.";

@Override
public String getDescription() {
return DESCRIPTION;
}

public static class InstanceHolder {
public static final ExcelProcessor INSTANCE = new ExcelProcessor();
}
}
```
```java
@NoArgsConstructor(access = AccessLevel.PRIVATE)
public class PDFProcessor implements FileProcessor {

static final String DESCRIPTION = "This is a PDF processor.";

@Override
public String getDescription() {
return DESCRIPTION;
}

public static class InstanceHolder {
public static final PDFProcessor INSTANCE = new PDFProcessor();
}
}
```
Factory Enum: FileProcessorType
```java
@RequiredArgsConstructor
@Getter
public enum FileProcessorType {
EXCEL(ExcelProcessor.InstanceHolder.INSTANCE),
PDF(PDFProcessor.InstanceHolder.INSTANCE);

private final FileProcessor instance;
}
```
Client Code
```java
public static void main(String[] args) {
LOGGER.info("Start processing files.");
var excel = FileProcessorType.EXCEL.getInstance();
var pdf = FileProcessorType.PDF.getInstance();
LOGGER.info(excel.getDescription());
LOGGER.info(pdf.getDescription());
}
```
Output
```
INFO: Start processing files.
INFO: This is an Excel processor.
INFO: This is a PDF processor.
```
## When to Use the Factory Enum Pattern

* When object types are known in advance and won't change frequently.

* When you want singleton instances per type.

* To avoid traditional factory classes and keep the logic self-contained within an enum.

* When readability and simplicity are preferred over extensibility.

## Benefits
* Type-safe and readable – enum provides compiler-checked safety.
* Singleton-friendly – each instance is created once and reused.
* No need for external factory class – the enum holds both the type and instance.
* Thread-safe by nature of enum and static holders.

## Trade-offs
* Not suitable for dynamic or extensible object types.
* Violates the Open/Closed Principle if new types are added frequently.
* Slightly unconventional compared to traditional Factory pattern.

## Related Patterns
* [Traditional Factory Method](https://java-design-patterns.com/patterns/factory/): Separates creation logic into a factory class.
* [Enum Singleton](https://www.baeldung.com/java-singleton#enum-singleton): Ensures one instance per type via enum.
* [Abstract Factory](https://java-design-patterns.com/patterns/abstract-factory/): Can be considered a kind of Factory that works with groups of products.
* [Service Locator](https://java-design-patterns.com/patterns/service-locator/): If you combine enum with lookup behavior.

## References and Credits
* [Design Patterns: Elements of Reusable Object-Oriented Software](https://amzn.to/3w0Rk5y)
* [Effective Java](https://amzn.to/4cGk2Jz)
* [Head First Design Patterns: Building Extensible and Maintainable Object-Oriented Software](https://amzn.to/3UpTLrG)
Binary file added factory-enum/etc/factory-sequence-diagram.png
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
Binary file added factory-enum/etc/factory.urm.png
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
38 changes: 38 additions & 0 deletions factory-enum/etc/factory.urm.puml
Original file line number Diff line number Diff line change
@@ -0,0 +1,38 @@
@startuml
package com.iluwatar.factory {

class App {
- LOGGER : Logger {static}
+ App()
+ main(args : String[]) {static}
}

interface FileProcessor {
+ getDescription() : String {abstract}
}

enum FileProcessorType {
+ EXCEL {static}
+ PDF {static}
- instance : FileProcessor
+ getInstance() : FileProcessor
+ valueOf(name : String) : FileProcessorType {static}
+ values() : FileProcessorType[] {static}
}

class ExcelProcessor {
~ DESCRIPTION : String {static}
+ ExcelProcessor()
+ getDescription() : String
}

class PDFProcessor {
~ DESCRIPTION : String {static}
+ PDFProcessor()
+ getDescription() : String
}
}

ExcelProcessor ..|> FileProcessor
PDFProcessor ..|> FileProcessor
@enduml
72 changes: 72 additions & 0 deletions factory-enum/pom.xml
Original file line number Diff line number Diff line change
@@ -0,0 +1,72 @@
<?xml version="1.0" encoding="UTF-8"?>
<!--
This project is licensed under the MIT license. Module model-view-viewmodel is using ZK framework licensed under LGPL (see lgpl-3.0.txt).
The MIT License
Copyright © 2014-2022 Ilkka Seppälä
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.
-->
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<parent>
<groupId>com.iluwatar</groupId>
<artifactId>java-design-patterns</artifactId>
<version>1.26.0-SNAPSHOT</version>
</parent>
<artifactId>factory-enum</artifactId>
<dependencies>
<dependency>
<groupId>org.slf4j</groupId>
<artifactId>slf4j-api</artifactId>
</dependency>
<dependency>
<groupId>ch.qos.logback</groupId>
<artifactId>logback-classic</artifactId>
</dependency>
<dependency>
<groupId>org.junit.jupiter</groupId>
<artifactId>junit-jupiter-engine</artifactId>
<scope>test</scope>
</dependency>
</dependencies>
<build>
<plugins>
<!-- Maven assembly plugin is invoked with default setting which we have
in parent pom and specifying the class having main method -->
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-assembly-plugin</artifactId>
<executions>
<execution>
<configuration>
<archive>
<manifest>
<mainClass>com.iluwatar.factory.App</mainClass>
</manifest>
</archive>
</configuration>
</execution>
</executions>
</plugin>
</plugins>
</build>
</project>
49 changes: 49 additions & 0 deletions factory-enum/src/main/java/com/iluwatar/factory/App.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,49 @@
/*
* This project is licensed under the MIT license. Module model-view-viewmodel is using ZK framework licensed under LGPL (see lgpl-3.0.txt).
*
* The MIT License
* Copyright © 2014-2022 Ilkka Seppälä
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*/
package com.iluwatar.factory;

import lombok.extern.slf4j.Slf4j;

/**
* The Factory Enum Pattern is a creational design pattern that leverages Java enums to encapsulate
* the creation logic of different object types. It promotes cleaner code by removing the need for
* separate factory classes and centralizing instantiation within type-safe enum constants.
*
* <p>In this example, different file processors (Excel, PDF) implement the same interface. The
* FileProcessorType enum holds the corresponding instance for each processor, allowing the client
* code to retrieve them in a clean and consistent way.
*/
@Slf4j
public class App {

/** Program main entry point. */
public static void main(String[] args) {
LOGGER.info("The alchemist begins his work.");
var excelProcessor = FileProcessorType.EXCEL.getInstance();
var pdfProcessor = FileProcessorType.PDF.getInstance();
LOGGER.info(excelProcessor.getDescription());
LOGGER.info(pdfProcessor.getDescription());
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,45 @@
/*
* This project is licensed under the MIT license. Module model-view-viewmodel is using ZK framework licensed under LGPL (see lgpl-3.0.txt).
*
* The MIT License
* Copyright © 2014-2022 Ilkka Seppälä
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*/
package com.iluwatar.factory;

import lombok.AccessLevel;
import lombok.NoArgsConstructor;

/** ExcelProcessor implementation. */
@NoArgsConstructor(access = AccessLevel.PRIVATE)
public class ExcelProcessor implements FileProcessor {

static final String DESCRIPTION = "This is a excel processor.";

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

minor suggestion-
this better be private and class property should be accesses only through getDescription


@Override
public String getDescription() {
return DESCRIPTION;
}

@NoArgsConstructor(access = AccessLevel.PRIVATE)
public static class InstanceHolder {
public static final ExcelProcessor INSTANCE = new ExcelProcessor();
}
}
31 changes: 31 additions & 0 deletions factory-enum/src/main/java/com/iluwatar/factory/FileProcessor.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,31 @@
/*
* This project is licensed under the MIT license. Module model-view-viewmodel is using ZK framework licensed under LGPL (see lgpl-3.0.txt).
*
* The MIT License
* Copyright © 2014-2022 Ilkka Seppälä
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*/
package com.iluwatar.factory;

/** FileProcessor interface. */
public interface FileProcessor {

String getDescription();
}
Loading
Loading