Abstract Factory Pattern
What is Abstract Factory Pattern?
Abstract Factory Pattern is a creational pattern that provides an interface for creating families of related or dependent objects without specifying their concrete classes.
When to use it?
Use Abstract factory pattern when you have families of objects where objects in one family are expected to work together, yet still want to decouple concrete products & their factories from client code.
Problem
We are planning to develop a simple theme application that client can choose light or dark UI based on their preference. We prepare three components Button, Menu and Toolbar. Each component has light & dark style appearances.
Obviously we want to make sure all light theme components work together (We don't want to display light button, dark menu and light toolbar at the same time). Additionally we want to remain possibility to add other theme in the future such as "High contrast" theme.
Solution
ThemeApplication
This is our client. The constructor receives concrete factory as its argument, then createComponents() will create corresponding components. Client only depends on an abstract factory & abstract products.ThemeFactory
An interface for all the concrete themes.Concrete ThemeFactories
Provides actual implementation for ThemeFactory's methods. These concrete factories create concrete products.Product interfaces
Interfaces for components.Concrete products
Defines specific behavior.
Structure
Implementation in Java
public interface Button { void render(); }
public class DarkButton implements Button{ @Override public void render() { System.out.println("Successfully render a dark button"); } }
public class LightButton implements Button { @Override public void render() { System.out.println("Successfully render a light button"); } }
You can write the code for Menu and Toolbar components in the same way.
public interface ThemeFactory { Button createButton(); Menu createMenu(); Toolbar createToolbar(); }
public class DarkThemeFactory implements ThemeFactory { @Override public Button createButton() { return new DarkButton(); } @Override public Menu createMenu() { return new DarkMenu(); } @Override public Toolbar createToolbar() { return new DarkToolbar(); } }
public class LightThemeFactory implements ThemeFactory { @Override public Button createButton() { return new LightButton(); } @Override public Menu createMenu() { return new LightMenu(); } @Override public Toolbar createToolbar() { return new LightToolbar(); } }
// This is our client code, notice client sees neither concrete products nor concrete factories public class ThemeApplication { private ThemeFactory themeFactory; private Button button; private Menu menu; private Toolbar toolbar; public ThemeApplication(ThemeFactory factory) { themeFactory = factory; createComponents(); } public void createComponents() { button = themeFactory.createButton(); menu = themeFactory.createMenu(); toolbar = themeFactory.createToolbar(); } public void renderComponents() { button.render(); menu.render(); toolbar.render(); } }
public class ThemeApplicationTestDrive { public static void main (String[] args) { ThemeFactory darkFactory = new DarkThemeFactory(); ThemeApplication app1 = new ThemeApplication(darkFactory); app1.renderComponents(); System.out.println("*******************"); ThemeFactory lightFactory = new LightThemeFactory(); ThemeApplication app2 = new ThemeApplication(lightFactory); app2.renderComponents(); } }
Output:
Successfully render a dark button Successfully render a dark menu Successfully render a dark toolbar ******************* Successfully render a light button Successfully render a light menu Successfully render a light toolbar
Pitfalls
- More complex to implement than factory pattern.
- Adding a new product requires changes in both abstract factory & concrete factories.
Comparison with Factory Pattern
- Factory pattern decouples concrete products from client code, while Abstract factory pattern hides concrete factories as well as concrete products.
- Factory pattern works with one product & its subclasses. In contrast, Abstract factory pattern is suitable when multiple products are expected to work together.
You can check all the design pattern implementations here.
GitHub Repository
P.S.
I'm new to write tech blog, if you have advice to improve my writing, or have any confusing point, please leave a comment!
Thank you for reading :)
The above is the detailed content of Abstract Factory Pattern. For more information, please follow other related articles on the PHP Chinese website!

Hot AI Tools

Undress AI Tool
Undress images for free

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

ArtGPT
AI image generator for creative art from text prompts.

Stock Market GPT
AI powered investment research for smarter decisions

Hot Article

Hot Tools

Notepad++7.3.1
Easy-to-use and free code editor

SublimeText3 Chinese version
Chinese version, very easy to use

Zend Studio 13.0.1
Powerful PHP integrated development environment

Dreamweaver CS6
Visual web development tools

SublimeText3 Mac version
God-level code editing software (SublimeText3)

Use the -cp parameter to add the JAR to the classpath, so that the JVM can load its internal classes and resources, such as java-cplibrary.jarcom.example.Main, which supports multiple JARs separated by semicolons or colons, and can also be configured through CLASSPATH environment variables or MANIFEST.MF.

UseFile.createNewFile()tocreateafileonlyifitdoesn’texist,avoidingoverwriting;2.PreferFiles.createFile()fromNIO.2formodern,safefilecreationthatfailsifthefileexists;3.UseFileWriterorPrintWriterwhencreatingandimmediatelywritingcontent,withFileWriterover

Use the implements keyword to implement the interface. The class needs to provide specific implementations of all methods in the interface. It supports multiple interfaces and is separated by commas to ensure that the methods are public. The default and static methods after Java 8 do not need to be rewrite.

JavaSPI is a built-in service discovery mechanism in JDK, and implements interface-oriented dynamic expansion through ServiceLoader. 1. Define the service interface and create a file with the full name of the interface under META-INF/services/, and write the fully qualified name of the implementation class; 2. Use ServiceLoader.load() to load the implementation class, and the JVM will automatically read the configuration and instantiate it; 3. The interface contract should be clarified during design, support priority and conditional loading, and provide default implementation; 4. Application scenarios include multi-payment channel access and plug-in verification; 5. Pay attention to performance, classpath, exception isolation, thread safety and version compatibility; 6. In Java9, provide can be used in combination with module systems.

This article explores in-depth the mechanism of sending multiple HTTP requests on the same TCP Socket, namely, HTTP persistent connection (Keep-Alive). The article clarifies the difference between HTTP/1.x and HTTP/2 protocols, emphasizes the importance of server-side support for persistent connections, and how to correctly handle Connection: close response headers. By analyzing common errors and providing best practices, we aim to help developers build efficient and robust HTTP clients.

Javagenericsprovidecompile-timetypesafetyandeliminatecastingbyallowingtypeparametersonclasses,interfaces,andmethods;wildcards(?,?extendsType,?superType)handleunknowntypeswithflexibility.1.UseunboundedwildcardwhentypeisirrelevantandonlyreadingasObject

This tutorial details how to efficiently process nested ArrayLists containing other ArrayLists in Java and merge all its internal elements into a single array. The article will provide two core solutions through the flatMap operation of the Java 8 Stream API: first flattening into a list and then filling the array, and directly creating a new array to meet the needs of different scenarios.

Use the Properties class to read Java configuration files easily. 1. Put config.properties into the resource directory, load it through getClassLoader().getResourceAsStream() and call the load() method to read the database configuration. 2. If the file is in an external path, use FileInputStream to load it. 3. Use getProperty(key,defaultValue) to handle missing keys and provide default values to ensure exception handling and input verification.
