Factory Method Pattern

Introduction to the Factory Method Pattern

Welcome back! So far, you've learned about design patterns and how they ensure structured and maintainable code. Now, we're moving on to an essential creational design pattern: the Factory Method Pattern. This pattern is all about creating objects in a more flexible way than direct instantiation. You'll learn how to implement your own factory methods to instantiate different types of objects and see how this pattern allows your code to handle new object types with ease.

Understanding the Factory Method Pattern

The Factory Method Pattern is a creational design pattern that provides an interface for creating an object but allows subclasses to alter the type of objects that will be created. This pattern promotes loose coupling by eliminating the need to specify the exact class of the object that will be created. Instead, the instantiation is handled by subclasses.

You should consider using the Factory Method Pattern when object creation requires conditional logic, when working with large class hierarchies, or when developing frameworks and libraries that need to allow users to extend and customize object creation.

Step 1: Using Abstract Classes and Methods in TypeScript

TypeScript provides native support for abstract classes and abstract methods using the abstract keyword. Abstract classes cannot be instantiated directly and can include abstract methods that must be implemented by derived classes.

TypeScript
abstract class AppDocument {
  abstract open(): void;
}

In this example, AppDocument is an abstract class with an abstract method open. Any subclass of AppDocument must provide an implementation for the open method.

Step 2: Create Concrete Subclasses

Next, create concrete subclasses of AppDocument. Each subclass will implement the open method. You can also use access modifiers and type annotations to make your code more robust.

class WordDocument extends AppDocument {
  open(): void {
    console.log("Opening Word document.");
  }
}

class ExcelDocument extends AppDocument {
  open(): void {
    console.log("Opening Excel document.");
  }
}

Step 3: Using Abstract Creator Classes in TypeScript

Sign up

Join the 1M+ learners on CodeSignal

Be a part of our community of 1M+ users who develop and demonstrate their skills on CodeSignal