00:00

Abstract Factory Design Pattern in Java

Last updated:

The abstract factory design pattern in Java is a creational pattern that creates families of related objects through one interface, without naming their concrete classes. The client picks one factory, such as "India checkout" or "PostgreSQL", and every object it gets from that factory is guaranteed to fit with the others.

Where a plain factory answers "which class should I create?", Abstract Factory answers "which set of classes belongs together?". Without it, code chooses each object separately, and sooner or later GST is calculated on an order printed in dollars. It is one of the creational design patterns.

1. What Is the Abstract Factory Design Pattern?

The GoF intent is: "Provide an interface for creating families of related or dependent objects without specifying their concrete classes."

A family is a group of objects that only make sense together: a tax rule and a currency format for one country, or a pagination syntax and a key strategy for one database. The pattern declares one interface with a create method per product, and writes one implementation of it per family.

The client receives a factory object, usually once at startup, and calls its methods whenever it needs a product. Because every product comes from the same factory, the family stays consistent. Switching to another family means passing a different factory; the client code does not change. In object-oriented terms, it applies "depend on abstractions" to a whole group of objects at once.

2. Key Components

ComponentResponsibilityIn the Basic Example
Abstract FactoryInterface with one creation method per productCheckoutKitFactory
Concrete FactoryCreates every product of one familyIndiaCheckoutKit, UsCheckoutKit
Abstract ProductInterface for one kind of productTaxCalculator, PriceFormatter
Concrete ProductOne family's implementation of a productGstTax, DollarFormatter
ClientUses only the abstract factory and abstract productsCheckoutService

The client holds an abstract factory reference. It calls the factory's methods, gets back abstract products, and makes the products work together. Only the concrete factory knows the concrete classes.

3. When Is Abstract Factory Useful?

  • Region-specific behaviour: an e-commerce store sells in several countries, and tax, currency and invoice layout must all follow the same country.
  • Supporting several vendors: a product runs on PostgreSQL, MySQL or Oracle, and each needs its own SQL for paging and keys.
  • Environment switching: the same service runs on AWS, Azure or a laptop, with storage and messaging that must come from the same platform.

4. UML Class Diagram

The diagram shows the Basic Example.

Abstract Factory UML class diagram CheckoutService uses the CheckoutKitFactory, TaxCalculator and PriceFormatter interfaces. IndiaCheckoutKit and UsCheckoutKit implement CheckoutKitFactory. GstTax and UsSalesTax implement TaxCalculator; RupeeFormatter and DollarFormatter implement PriceFormatter. IndiaCheckoutKit creates GstTax and RupeeFormatter; UsCheckoutKit creates UsSalesTax and DollarFormatter. CheckoutService + summary(cart): String uses «interface» CheckoutKitFactory + createTaxCalculator(): TaxCalculator + createPriceFormatter(): PriceFormatter «interface» TaxCalculator + tax(amount): BigDecimal + label(): String «interface» PriceFormatter + format(amount): String implements implements implements IndiaCheckoutKit UsCheckoutKit GstTax UsSalesTax RupeeFormatter DollarFormatter «create» India family «create» US family
Abstract Factory: each concrete factory creates one product of every kind, and all of them belong to the same family.
  1. CheckoutService depends on three interfaces only (dashed "uses" arrows).
  2. CheckoutKitFactory has one creation method per abstract product.
  3. Dashed lines with hollow triangles mean "implements": two concrete factories and two concrete products per product interface.
  4. The coloured «create» arrows show the families: IndiaCheckoutKit creates only India products, and UsCheckoutKit only US products.

5. Step-by-Step Execution Flow

  1. At startup the application chooses a concrete factory, for example new IndiaCheckoutKit(), from configuration.
  2. It passes the factory to CheckoutService as a CheckoutKitFactory.
  3. The service calls createTaxCalculator() and receives a GstTax, typed as TaxCalculator.
  4. It calls createPriceFormatter() on the same factory and receives a RupeeFormatter.
  5. On each order, the service calculates the tax and formats the amounts. The two products agree because they came from one factory.

6. Real-World Use Cases

  • E-commerce: per-country kits of tax rules, currency format, address validation and invoice template.
  • Payments and banking: a provider kit that creates the matching payment client, refund client and webhook signature verifier for one provider.
  • Notifications: a brand kit that creates email, SMS and push templates in the same tone and language.
  • The JDK: java.sql.Connection behaves like an abstract factory. createStatement(), prepareStatement() and createBlob() return interface types, and each JDBC driver supplies its own matching implementations.
  • Spring Boot: two @Configuration classes guarded by @Profile("aws") and @Profile("azure") each define a matching set of beans. Activating a profile swaps the whole family, which is the Abstract Factory idea applied through configuration.

7. Problem Without the Pattern

Here the tax and the currency are chosen by separate settings:

CheckoutWithoutAbstractFactory.java
import java.math.BigDecimal;
import java.math.RoundingMode;

public class CheckoutWithoutAbstractFactory {

    static BigDecimal addTax(String taxRegion, BigDecimal amount) {
        if ("IN".equals(taxRegion)) {
            return amount.multiply(new BigDecimal("1.18"));       // GST 18%
        } else if ("US".equals(taxRegion)) {
            return amount.multiply(new BigDecimal("1.0725"));     // example 7.25% sales tax
        }
        throw new IllegalArgumentException("Unknown tax region: " + taxRegion);
    }

    static String format(String currencyRegion, BigDecimal amount) {
        BigDecimal rounded = amount.setScale(2, RoundingMode.HALF_UP);
        if ("IN".equals(currencyRegion)) {
            return "Rs. " + rounded;
        } else if ("US".equals(currencyRegion)) {
            return "$" + rounded;
        }
        throw new IllegalArgumentException("Unknown currency region: " + currencyRegion);
    }

    public static void main(String[] args) {
        BigDecimal cart = new BigDecimal("1000.00");
        System.out.println("India order: " + format("IN", addTax("IN", cart)));

        // Two independent settings: nothing stops a mismatched pair
        System.out.println("Buggy order: " + format("US", addTax("IN", cart)));
    }
}
Console
India order: Rs. 1180.00
Buggy order: $1180.00
  • Inconsistent families: the second order adds Indian GST and prints dollars, and nothing catches it.
  • Duplication: every method repeats the same if ("IN") ... else if ("US") chain.
  • Poor maintainability: adding Germany means finding and editing every chain.
  • Tight coupling: business code knows every regional rule.

8. Solution Using the Pattern

Group the related objects into a kit. One CheckoutKitFactory interface creates the tax calculator and the formatter, and one concrete factory per country creates both.

A mismatch is now impossible by construction: the service receives one factory, so it cannot combine GST with dollars. The country check happens once, when the factory is chosen. Adding Germany means one new factory and its products; CheckoutService stays untouched. Tests can pass a test kit.

9. Abstract Factory Design Pattern in Java: Code Examples

Each example is a single file that runs on Java 21 with java FileName.java.

Basic Example: Regional Checkout Kits

Problem: fix the mismatch from section 7 so that tax and currency always come from the same country.

CheckoutKitDemo.java
import java.math.BigDecimal;
import java.math.RoundingMode;
import java.util.List;

public class CheckoutKitDemo {

    // Abstract products
    interface TaxCalculator {
        BigDecimal tax(BigDecimal amount);
        String label();
    }

    interface PriceFormatter {
        String format(BigDecimal amount);
    }

    // India family
    static final class GstTax implements TaxCalculator {
        public BigDecimal tax(BigDecimal amount) { return amount.multiply(new BigDecimal("0.18")); }
        public String label() { return "GST 18%"; }
    }

    static final class RupeeFormatter implements PriceFormatter {
        public String format(BigDecimal amount) { return "Rs. " + amount.setScale(2, RoundingMode.HALF_UP); }
    }

    // US family
    static final class UsSalesTax implements TaxCalculator {
        public BigDecimal tax(BigDecimal amount) { return amount.multiply(new BigDecimal("0.0725")); }
        public String label() { return "Sales tax 7.25%"; }
    }

    static final class DollarFormatter implements PriceFormatter {
        public String format(BigDecimal amount) { return "$" + amount.setScale(2, RoundingMode.HALF_UP); }
    }

    // Abstract factory: one method per product in the family
    interface CheckoutKitFactory {
        TaxCalculator createTaxCalculator();
        PriceFormatter createPriceFormatter();
    }

    // Concrete factories: each one creates a matching family
    static final class IndiaCheckoutKit implements CheckoutKitFactory {
        public TaxCalculator createTaxCalculator() { return new GstTax(); }
        public PriceFormatter createPriceFormatter() { return new RupeeFormatter(); }
    }

    static final class UsCheckoutKit implements CheckoutKitFactory {
        public TaxCalculator createTaxCalculator() { return new UsSalesTax(); }
        public PriceFormatter createPriceFormatter() { return new DollarFormatter(); }
    }

    // Client: sees only the abstract factory and abstract products
    static final class CheckoutService {
        private final TaxCalculator taxCalculator;
        private final PriceFormatter formatter;

        CheckoutService(CheckoutKitFactory kit) {
            this.taxCalculator = kit.createTaxCalculator();     // both objects come from the same family
            this.formatter = kit.createPriceFormatter();
        }

        String summary(BigDecimal cart) {
            BigDecimal tax = taxCalculator.tax(cart);
            return "cart %s + %s %s = %s".formatted(formatter.format(cart), taxCalculator.label(),
                    formatter.format(tax), formatter.format(cart.add(tax)));
        }
    }

    public static void main(String[] args) {
        BigDecimal cart = new BigDecimal("1000.00");
        for (CheckoutKitFactory kit : List.of(new IndiaCheckoutKit(), new UsCheckoutKit())) {
            CheckoutService checkout = new CheckoutService(kit);
            System.out.println(kit.getClass().getSimpleName() + ": " + checkout.summary(cart));
        }
    }
}

Important classes and methods

  • CheckoutKitFactory is the abstract factory; its two methods are the family's products.
  • IndiaCheckoutKit and UsCheckoutKit are concrete factories.
  • CheckoutService takes one kit in its constructor, so both products always match.

Expected output

Console
IndiaCheckoutKit: cart Rs. 1000.00 + GST 18% Rs. 180.00 = Rs. 1180.00
UsCheckoutKit: cart $1000.00 + Sales tax 7.25% $72.50 = $1072.50

How it runs

  1. main loops over the two kits.
  2. Each CheckoutService asks its kit for a tax calculator and a formatter.
  3. summary() computes 18% or 7.25% of 1000.00 and formats every amount in the kit's currency.

10. Best Practices and Common Mistakes

Best practices

  • Choose the concrete factory once, at startup or in configuration, and inject it.
  • Keep each family small: only products that truly must match.
  • Stateless concrete factories can be shared singletons, for example as Spring beans.
  • Thread safety: if a factory caches products, they must be immutable or thread-safe, as in the Enterprise Example.

Common mistakes

  • Overengineering: using Abstract Factory when there is one family, or when the products do not depend on each other.
  • Mixing factories by getting one product from one kit and another from a different kit.
  • Type checks such as instanceof GstTax in the client.
  • Huge factory interfaces that every family must implement in full.

11. When to Use and When Not to Use

Use it when wrong combinations would be a real bug, when the set of families is expected to grow, or when a whole platform must be swappable for tests.

Avoid it when the products vary independently, when you have a single family, or when new kinds of product are added often, since each one changes every factory. A dependency injection profile may already cover simple cases.

12. Advantages and Disadvantages

Advantages

  • Guaranteed consistency within a family.
  • Loose coupling: clients see interfaces only.
  • Easy family swap by changing one object.
  • New families without touching clients (Open/Closed).

Disadvantages

  • New product kinds are expensive: every factory must change.
  • Many classes: families × products, plus factories.
  • More indirection for readers new to the code.

13. Comparison with Similar Patterns

AspectAbstract FactoryFactory MethodBuilder
CreatesA family of related productsOne productOne complex product
MechanismComposition: the client holds a factory objectInheritance: a subclass overrides a methodStep-by-step calls, then build()
Variation pointWhich familyWhich single classWhich settings
Easy to addA new familyA new product subclassA new optional setting

Choose Factory Method for one varying product, Abstract Factory when several products must vary together, and Builder when the difficulty is assembling one object. They combine: concrete factories often implement each creation method as a factory method, and are often singletons. Prototype is an alternative that clones preconfigured objects instead of subclassing factories.

14. Summary

  • The abstract factory design pattern in Java creates families of related objects through one interface.
  • Purpose: keep products consistent and hide their concrete classes.
  • Components: Abstract Factory, Concrete Factory, Abstract Product, Concrete Product, Client.
  • The client gets one factory and requests every product from it.
  • Used for regional rules, database dialects, cloud platforms and Spring profiles.
  • Benefits: consistency, loose coupling, easy family swaps.
  • Cost: adding a new product kind touches every factory.

15. Java Design Pattern Interview Questions and Answers

Q1. You must add a ShippingCalculator to every family. What changes, and can a default method help?

The abstract factory gets a new createShippingCalculator() method, and every concrete factory must implement it. A Java default method avoids touching every class, but it gives all families the same fallback, which can silently break consistency. Leaving the method abstract is usually safer, because the compiler then lists every factory that needs updating.

Q2. How can an enum implement an abstract factory?

Each constant is one concrete factory. You get exactly one instance per family, thread-safe by design, and easy lookup with valueOf().

enum RegionKit implements CheckoutKitFactory {
    INDIA {
        public TaxCalculator createTaxCalculator() { return new GstTax(); }
        public PriceFormatter createPriceFormatter() { return new RupeeFormatter(); }
    },
    US {
        public TaxCalculator createTaxCalculator() { return new UsSalesTax(); }
        public PriceFormatter createPriceFormatter() { return new DollarFormatter(); }
    }
}
Q3. How would you switch a whole family of beans in Spring Boot?

Put each family in its own @Configuration class and activate one with @Profile or @ConditionalOnProperty. Each configuration class acts as a concrete factory, and clients inject only the interfaces.

@Configuration
@Profile("aws")
class AwsCloudConfig {
    @Bean BlobStorage storage() { return new S3Storage("invoices-prod"); }
    @Bean EventPublisher events() { return new SnsPublisher(); }
}
Q4. One family cannot support a product, for example a local setup with no message queue. What do you do?

Return a Null Object, such as a publisher that only logs, so clients need no special cases. Throwing UnsupportedOperationException pushes the problem onto every caller. If several families lack the product, the family is too wide: split the factory into smaller interfaces (Interface Segregation Principle).

Q5. How do you unit-test a service that depends on an abstract factory?

Create a test family: a small factory that returns fakes or stubs with fixed results, and pass it to the service's constructor. Because the service only knows the interfaces, no mocking framework or real infrastructure is needed, and assertions can inspect what the fakes recorded.