Factory
Factory is a pattern that provides a way to create objects without specifying the exact class of object that will be created.
The Factory pattern is used when you need to create objects of different types based on some input or configuration. It provides a way to create objects without exposing the creation logic to the client code.
Example
interface Product {
operation(): string;
}
class ConcreteProduct1 implements Product {
public operation(): string {
return "ConcreteProduct1";
}
}
class ConcreteProduct2 implements Product {
public operation(): string {
return "ConcreteProduct2";
}
}
abstract class Creator {
public abstract factoryMethod(): Product;
public someOperation(): string {
const product = this.factoryMethod();
return `Creator: The same creator's code has just worked with ${product.operation()}`;
}
}
class ConcreteCreator1 extends Creator {
public factoryMethod(): Product {
return new ConcreteProduct1();
}
}
class ConcreteCreator2 extends Creator {
public factoryMethod(): Product {
return new ConcreteProduct2();
}
}
function clientCode(creator: Creator) {
console.log(
"Client: I'm not aware of the creator's class, but it still works."
);
console.log(creator.someOperation());
}
console.log("App: Launched with the ConcreteCreator1.");
clientCode(new ConcreteCreator1());
console.log("");
console.log("App: Launched with the ConcreteCreator2.");
clientCode(new ConcreteCreator2());Output
App: Launched with the ConcreteCreator1.
Client: I'm not aware of the creator's class, but it still works.
Creator: The same creator's code has just worked with ConcreteProduct1Last updated on