Abstract Factory Design Pattern

Back To Index

Overview

The Abstract Factory Design Pattern provides an interface for creating families of related or dependent objects without specifying their concrete classes. It is often used when the system needs to create multiple families of products.

Key Characteristics

Implementation

The following is an example of an Abstract Factory implementation in Java:


// Abstract product interfaces
interface Chair {
    void sitOn();
}

interface Table {
    void use();
}

// Concrete products
class ModernChair implements Chair {
    @Override
    public void sitOn() {
        System.out.println("Sitting on a modern chair.");
    }
}

class VictorianChair implements Chair {
    @Override
    public void sitOn() {
        System.out.println("Sitting on a Victorian chair.");
    }
}

class ModernTable implements Table {
    @Override
    public void use() {
        System.out.println("Using a modern table.");
    }
}

class VictorianTable implements Table {
    @Override
    public void use() {
        System.out.println("Using a Victorian table.");
    }
}

// Abstract factory
interface FurnitureFactory {
    Chair createChair();
    Table createTable();
}

// Concrete factories
class ModernFurnitureFactory implements FurnitureFactory {
    @Override
    public Chair createChair() {
        return new ModernChair();
    }

    @Override
    public Table createTable() {
        return new ModernTable();
    }
}

class VictorianFurnitureFactory implements FurnitureFactory {
    @Override
    public Chair createChair() {
        return new VictorianChair();
    }

    @Override
    public Table createTable() {
        return new VictorianTable();
    }
}
    

When to Use

Advantages

Disadvantages

Back To Index