Design Patterns - Static Factory Method Pattern

The static factory method is a creational design pattern to create instances of a class, it works like the factory method, but unlike this one, the static factory method just consists of a static method within the class.

This creational design pattern is especially useful in certain scenarios, for example, when the constructor is private.

Table of Contents

  1. Static Factory Method pattern in C#
  2. Static Factory Method pattern in TypeScript

Static Factory Method pattern in C#

public class User
{
  private string firstName;
  private string lastName;
  private string email;

  private User(string firstName, string lastName, string email)
  {
    this.firstName: firstName;
    this.lastName: lastName;
    this.email: email;
  }

  public string GetFirstName() { return this.firstName; }
  public string GetLastName() { return this.lastName; }
  public string GetEmail() { return this.email; }

  public static User Create(string firstName, string lastName, string email)
  {
    return new User(firstName, lastName, email);
  }
};

About this code snippet:

  • The constructor is private.
  • To create new instances of the user class, just use the static factory method with: User.Create("John", "Doe", "john@doe.com").

Static Factory Method pattern in TypeScript

class User {
  private firstName: string;
  private lastName: string;
  private email: string;

  get getFirstName(): string {
    return this.firstName;
  }
  get getLastName(): string {
    return this.lastName;
  }
  get getEmail(): string {
    return this.email;
  }

  private constructor(firstName: string, lastName: string, email: string) {
    this.firstName: firstName;
    this.lastName: lastName;
    this.email: email;
  }

  static create(firstName: string, lastName: string, email: string): User {
    return new User(firstName, lastName, email);
  }
}

About this code snippet:

  • The constructor is private.
  • To create new instances of the user class, just use the static factory method with: User.create("John", "Doe", "john@doe.com").