The generic factory pattern helps create objects without specifying exact classes. It makes code flexible and reusable.
0
0
Generic factory pattern in Typescript
Introduction
When you want to create different types of objects using the same code.
When you need to add new object types without changing existing code.
When you want to separate object creation from usage.
When you want to manage object creation logic in one place.
When you want to use type safety with different object types.
Syntax
Typescript
interface Factory<T> {
create(): T;
}
class ConcreteFactory<T> implements Factory<T> {
constructor(private creator: () => T) {}
create(): T {
return this.creator();
}
}The Factory interface defines a method to create objects of type T.
The ConcreteFactory class takes a function that creates objects and uses it to produce new instances.
Examples
This interface says any factory must have a
create method that returns an object of type T.Typescript
interface Factory<T> {
create(): T;
}This class uses a function passed in the constructor to create objects of type
T.Typescript
class ConcreteFactory<T> implements Factory<T> { constructor(private creator: () => T) {} create(): T { return this.creator(); } }
Here, we create a factory for
Dog objects and use it to make a dog that can speak.Typescript
class Dog { speak() { return 'Woof!'; } } const dogFactory = new ConcreteFactory(() => new Dog()); const dog = dogFactory.create(); console.log(dog.speak());
Sample Program
This program defines a generic factory pattern to create Cat and Dog objects. Each factory uses a function to create the right animal. Then it calls speak() on each animal.
Typescript
interface Factory<T> {
create(): T;
}
class ConcreteFactory<T> implements Factory<T> {
constructor(private creator: () => T) {}
create(): T {
return this.creator();
}
}
class Cat {
speak() { return 'Meow!'; }
}
class Dog {
speak() { return 'Woof!'; }
}
const catFactory = new ConcreteFactory(() => new Cat());
const dogFactory = new ConcreteFactory(() => new Dog());
const cat = catFactory.create();
const dog = dogFactory.create();
console.log(cat.speak());
console.log(dog.speak());OutputSuccess
Important Notes
You can use arrow functions or normal functions as creators.
This pattern helps keep your code clean and easy to extend.
Using generics ensures type safety when creating objects.
Summary
The generic factory pattern creates objects without knowing their exact class.
It uses a generic interface and a creator function to make objects.
This pattern makes your code flexible and easy to add new types.