React-TypeScript Design Pattern 3 - Creational Design Patterns - Prototype, Singleton

Fatemeh Paghar - May 21 '23 - - Dev Community

Design Pattern - Prototype

One way to generate new objects by copying old ones is the prototyping pattern. Instead of creating something from scratch, you can copy an existing unit (called a "prototype"). This is useful when creating something new requires more effort or time than simply copying an existing object. A prototype serves as a model or specification for producing a replica.

In practice, a prototype is an example or model used to make other similar things. The new thing, often called a "clone," inherits the characteristics of the prototype but can be changed or customized as needed. This mode is useful when making something new requires a lot of work or is complex. Copying existing examples makes creating new things more efficient and easier to manage.

The main idea is not only to copy the appearance of an object, but to create a new object that is independent and can be changed without affecting the original or other copies. Prototyping pattern is a useful tool when you need to create a lot of similar things or when creating something new from scratch is too complex.

import React, { useState } from 'react';

// Product: Art Piece (Prototype)
class ArtPiece {
  constructor(public color: string, public shape: string) {}

  clone(): ArtPiece {
    // Creating a new instance by copying the current state
    return new ArtPiece(this.color, this.shape);
  }

  describe(): string {
    return `Piece with color ${this.color} and shape ${this.shape}`;
  }
}

// Concrete Prototype: Blue Square Art Piece
const blueSquarePrototype = new ArtPiece('blue', 'square');

// React Component using the Prototype pattern
function ArtComponent() {
  const [artPiece, setArtPiece] = useState<ArtPiece | null>(null);

  const createNewPiece = () => {
    // Creating a new piece by cloning the prototype
    const newPiece = blueSquarePrototype.clone();
    setArtPiece(newPiece);
  };

  return (
    <div>
      <h1>Art Piece Details</h1>
      {artPiece ? (
        <div>
          <p>{artPiece.describe()}</p>
        </div>
      ) : (
        <p>No art piece created yet</p>
      )}
      <button onClick={createNewPiece}>Create Art Piece</button>
    </div>
  );
}

export default ArtComponent;

Enter fullscreen mode Exit fullscreen mode

In this example:

'ArtPiece' is the prototype class that represents art pieces. It has a "clone" method to create a copy of itself.
'blueSquarePrototype' is an instance of the concrete prototype (blue square art piece) used to create new instances.
The React component 'ArtComponent' has a button for creating a new art piece. It uses the prototype pattern by cloning 'blueSquarePrototype' to generate new instances.
This example shows how to apply the prototype pattern to create a copy of an existing object, providing a way to efficiently create new instances based on a predefined prototype.

Design Pattern - Singleton

The singleton design pattern is a method in software design and belongs to the category of creation patterns. Its main purpose is to ensure that there is only one instance of a class and provide a central access point for that specific instance. This pattern proves particularly useful when only one object is needed to monitor and coordinate the operation of the entire system. The most common use cases include scenarios where a single entity (such as a configuration manager, logging service, or connection pool) needs to be shared and consistently accessible by different components of the system.

Essentially, the singleton pattern ensures that a class has a single instance by controlling its instantiation process. This instance can then be accessed globally, providing a consistent and standardized way for different parts of the system to interact with and consume the shared resource or service. By centralizing control over this unique instance, the singleton pattern improves coordination and consistency between applications, prevents the creation of multiple instances, and enables efficient management of shared resources.

In practice, the Singleton pattern helps simplify the management of key system components that should have a single existence, thereby preventing unnecessary duplication and promoting a more organized and efficient code structure. However, it should be used with caution, as improper use of the singleton pattern can lead to global health issues and affect the testability and maintainability of the code.

import React, { useState } from 'react';

// Singleton: Art Manager
class ArtManager {
  private static instance: ArtManager | null = null;

  private constructor() {
    // Private constructor to prevent direct instantiation
  }

  static getInstance(): ArtManager {
    // Creating or returning the existing instance
    if (!ArtManager.instance) {
      ArtManager.instance = new ArtManager();
    }
    return ArtManager.instance;
  }

  createArtPiece(): string {
    // Simulating the creation of an art piece
    return 'New art piece created!';
  }
}

// React Component using the Singleton pattern
function ArtComponent() {
  const [artPieceMessage, setArtPieceMessage] = useState<string | null>(null);

  const createNewPiece = () => {
    // Using the Singleton to create an art piece
    const artManager = ArtManager.getInstance();
    const newPieceMessage = artManager.createArtPiece();
    setArtPieceMessage(newPieceMessage);
  };

  return (
    <div>
      <h1>Art Piece Creation</h1>
      {artPieceMessage && <p>{artPieceMessage}</p>}
      <button onClick={createNewPiece}>Create Art Piece</button>
    </div>
  );
}

export default ArtComponent;
Enter fullscreen mode Exit fullscreen mode

In this example:

'ArtPieceManager' is a Singleton class responsible for managing art piece-related operations. It has a private constructor to prevent direct instantiation, and a static method 'getInstance' to get or create an instance if it does not exist.

The React component 'ArtPieceComponent' uses the singleton 'ArtPieceManager' to create art pieces. When the Create Art Piece button is clicked, the singleton's createArtPiece method is called.
This example shows how the Singleton pattern ensures that there is only one instance of 'ArtPieceManager' in the entire application, providing a global access point to art piece-related functionality. Note that the singleton pattern is typically used to centrally manage shared resources or state.

. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .