Abstract Factory Pattern
The Abstract Factory Pattern is a creational design pattern that provides an interface for creating families of related or dependent objects without specifying their concrete classes. It allows a client to create objects without specifying their concrete classes, supporting the creation of products that conform to a particular theme or variation.
Key features of the Abstract Factory Pattern:
Abstract Factory Interface
Concrete Factories
Abstract Product Interface
Concrete Products
Client
Abstract Factory Interface
Declares an interface for creating a family of products.
Concrete Factories
Implement the Abstract Factory interface to produce families of related products.
Abstract Product Interface
Declares interfaces for a set of distinct but related products.
Concrete Products
Implement the Abstract Product interfaces and define specific product types.
Client
Uses the Abstract Factory and Abstract Product interfaces for creating families of related or dependent objects.
Example
// Abstract Product interfaces
interface Engine {
horsepower: number;
}
interface Tire {
diameter: number;
}
// Abstract Factory interface
interface CarFactory {
createEngine(): Engine;
createTire(): Tire;
}
// Concrete Products
class SportsCarEngine implements Engine {
horsepower = 500;
}
class SportsCarTire implements Tire {
diameter = 18;
}
class SUVEngine implements Engine {
horsepower = 300;
}
class SUVTire implements Tire {
diameter = 20;
}
// Concrete Factories
class SportsCarFactory implements CarFactory {
createEngine(): Engine {
return new SportsCarEngine();
}
createTire(): Tire {
return new SportsCarTire();
}
}
class SUVFactory implements CarFactory {
createEngine(): Engine {
return new SUVEngine();
}
createTire(): Tire {
return new SUVTire();
}
}
// Client
function buildCar(factory: CarFactory): { engine: Engine, tire: Tire } {
const engine = factory.createEngine();
const tire = factory.createTire();
return { engine, tire };
}
// Usage
const sportsCar = buildCar(new SportsCarFactory());
console.log(sportsCar);
const suv = buildCar(new SUVFactory());
console.log(suv);
In this example, we have an abstract factory CarFactory with methods to create an Engine and a Tire. Concrete factories (SportsCarFactory and SUVFactory) implement this interface to produce specific products (SportsCarEngine, SportsCarTire, SUVEngine, SUVTire). The client (buildCar function) can use different factories to create cars with different configurations.