---
title: "Abstract Factory Pattern in Java: Mastering Object Creation Elegantly"
shortTitle: Abstract Factory
description: "Learn the Abstract Factory pattern in Java with real-world examples, class diagrams, and tutorials. Understand its intent, applicability, benefits, and known uses to enhance your design pattern knowledge."
category: Creational
language: en
tag:
- Abstraction
- Decoupling
- Gang of Four
- Instantiation
- Polymorphism
---
## Also known as
* Kit
## Intent of Abstract Factory Design Pattern
The Abstract Factory pattern in Java provides an interface for creating families of related or dependent objects without specifying their concrete classes, enhancing modularity and flexibility in software design.
## Detailed Explanation of Abstract Factory Pattern with Real-World Examples
Real-world example
> Imagine a furniture company that uses the Abstract Factory pattern in Java to produce various styles of furniture: modern, Victorian, and rustic. Each style includes products like chairs, tables, and sofas. To ensure consistency within each style, the company uses an Abstract Factory pattern.
>
> In this scenario, the Abstract Factory is an interface for creating families of related furniture objects (chairs, tables, sofas). Each concrete factory (ModernFurnitureFactory, VictorianFurnitureFactory, RusticFurnitureFactory) implements the Abstract Factory interface and creates a set of products that match the specific style. This way, clients can create a whole set of modern or Victorian furniture without worrying about the details of their instantiation. This maintains a consistent style and allows easy swapping of one style of furniture for another.
In plain words
> A factory of factories; a factory that groups the individual but related/dependent factories together without specifying their concrete classes.
Wikipedia says
> The abstract factory pattern provides a way to encapsulate a group of individual factories that have a common theme without specifying their concrete classes
## Programmatic Example of Abstract Factory in Java
To create a kingdom using the Abstract Factory pattern in Java, we need objects with a common theme. The elven kingdom needs an elven king, elven castle, and elven army whereas the orcish kingdom needs an orcish king, orcish castle, and orcish army. There is a dependency between the objects in the kingdom.
Translating the kingdom example above. First of all, we have some interfaces and implementation for the objects in the kingdom.
```java
public interface Castle {
String getDescription();
}
public interface King {
String getDescription();
}
public interface Army {
String getDescription();
}
// Elven implementations ->
public class ElfCastle implements Castle {
static final String DESCRIPTION = "This is the elven castle!";
@Override
public String getDescription() {
return DESCRIPTION;
}
}
public class ElfKing implements King {
static final String DESCRIPTION = "This is the elven king!";
@Override
public String getDescription() {
return DESCRIPTION;
}
}
public class ElfArmy implements Army {
static final String DESCRIPTION = "This is the elven Army!";
@Override
public String getDescription() {
return DESCRIPTION;
}
}
// Orcish implementations similarly -> ...
```
Then we have the abstraction and implementations for the kingdom factory.
```java
public interface KingdomFactory {
Castle createCastle();
King createKing();
Army createArmy();
}
public class ElfKingdomFactory implements KingdomFactory {
@Override
public Castle createCastle() {
return new ElfCastle();
}
@Override
public King createKing() {
return new ElfKing();
}
@Override
public Army createArmy() {
return new ElfArmy();
}
}
// Orcish implementations similarly -> ...
```
Now, we can design a factory for our different kingdom factories. In this example, we created `FactoryMaker`, responsible for returning an instance of either `ElfKingdomFactory` or `OrcKingdomFactory`. The client can use `FactoryMaker` to create the desired concrete factory which, in turn, will produce different concrete objects (derived from `Army`, `King`, `Castle`). In this example, we also used an enum to parameterize which type of kingdom factory the client will ask for.
```java
public static class FactoryMaker {
public enum KingdomType {
ELF, ORC
}
public static KingdomFactory makeFactory(KingdomType type) {
return switch (type) {
case ELF -> new ElfKingdomFactory();
case ORC -> new OrcKingdomFactory();
};
}
}
```
Here is the main function of our example application:
```java
LOGGER.info("elf kingdom");
createKingdom(Kingdom.FactoryMaker.KingdomType.ELF);
LOGGER.info(kingdom.getArmy().getDescription());
LOGGER.info(kingdom.getCastle().getDescription());
LOGGER.info(kingdom.getKing().getDescription());
LOGGER.info("orc kingdom");
createKingdom(Kingdom.FactoryMaker.KingdomType.ORC);
LOGGER.info(kingdom.getArmy().getDescription());
LOGGER.info(kingdom.getCastle().getDescription());
LOGGER.info(kingdom.getKing().getDescription());
```
The program output:
```
07:35:46.340 [main] INFO com.iluwatar.abstractfactory.App -- elf kingdom
07:35:46.343 [main] INFO com.iluwatar.abstractfactory.App -- This is the elven army!
07:35:46.343 [main] INFO com.iluwatar.abstractfactory.App -- This is the elven castle!
07:35:46.343 [main] INFO com.iluwatar.abstractfactory.App -- This is the elven king!
07:35:46.343 [main] INFO com.iluwatar.abstractfactory.App -- orc kingdom
07:35:46.343 [main] INFO com.iluwatar.abstractfactory.App -- This is the orc army!
07:35:46.343 [main] INFO com.iluwatar.abstractfactory.App -- This is the orc castle!
07:35:46.343 [main] INFO com.iluwatar.abstractfactory.App -- This is the orc king!
```
## Abstract Factory Pattern Class Diagram

## When to Use the Abstract Factory Pattern in Java
Use the Abstract Factory pattern in Java when:
* The system should be independent of how its products are created, composed, and represented.
* You need to configure the system with one of multiple families of products.
* A family of related product objects must be used together, enforcing consistency.
* You want to provide a class library of products, exposing only their interfaces, not their implementations.
* The lifetime of dependencies is shorter than the consumer's lifetime.
* Dependencies need to be constructed using runtime values or parameters.
* You need to choose which product to use from a family at runtime.
* Adding new products or families should not require changes to existing code.
## Abstract Factory Pattern Java Tutorials
* [Abstract Factory Design Pattern in Java (DigitalOcean)](https://www.digitalocean.com/community/tutorials/abstract-factory-design-pattern-in-java)
* [Abstract Factory(Refactoring Guru)](https://refactoring.guru/design-patterns/abstract-factory)
## Benefits and Trade-offs of Abstract Factory Pattern
Benefits:
* Flexibility: Easily switch between product families without code modifications.
* Decoupling: Client code only interacts with abstract interfaces, promoting portability and maintainability.
* Reusability: Abstract factories and products facilitate component reuse across projects.
* Maintainability: Changes to individual product families are localized, simplifying updates.
Trade-offs:
* Complexity: Defining abstract interfaces and concrete factories adds initial overhead.
* Indirectness: Client code interacts with products indirectly through factories, potentially reducing transparency.

道长不会写代码
- 粉丝: 2551
最新资源
- Steam 销售历史数据集
- ️ 网络安全基础知识思维导图、大学笔记(Network security Mind Map)(1).zip
- goby poc or exp,分享goby最新网络安全漏洞检测或利用代码(1).zip
- 华中科技大学-网络空间安全学院-编译原理实验-2021秋.zip
- 为了方便安全从业人员在使用网络测绘平台进行信息搜集时的效率,本程序集合了多个网络测绘平台,可以快速在多个网络测绘平台搜索
- 本存储库包含了多个用于学习网络安全的脚本.zip
- 收集的一些国外能提供提供威胁情报的公司,涵盖网络安全、工控安全、终端安全、移动安全等领域(1).zip
- 网络安全与渗透测试工具导航.zip
- 一份网络安全入门的资料。.zip
- CCMAP是一个用C语言编写的高性能端口扫描工具,支持多种扫描方式和IP范围扫描,可用于网络安全评估和系统管理。.zip
- 大数据与网络安全实验室管理系统.zip
- 在当前的数字时代,随着网络攻击日益复杂和频繁,网络安全成为了保障信息安全的重中之重。尤其是在网络入侵检测领域,传统的基于
- 微众银行多方大数据隐私计算平台基于区块链、安全多方计算、联合建模等技术构建密态计算网络,实现原始数据不出域,数据可用不可
- 网络安全相关的RSS订阅列表(1).zip
- 重庆大学网络空间安全实验室推荐会议和期刊目录.zip
资源上传下载、课程学习等过程中有任何疑问或建议,欢迎提出宝贵意见哦~我们会及时处理!
点击此处反馈


