Gangs of Four (GoF) Design Patterns

Today, I discussed Design Patterns, their types, the GoF design patterns, drawbacks, and benefits for backend engineers.

In partnership with

Hello “👋”

Welcome to another week, another opportunity to become a Great Backend Engineer.

Today’s issue is brought to you by Masteringbackend → A great resource for backend engineers. We offer next-level backend engineering training and exclusive resources.

Before we get started, I have a few announcements:

We recently launched the first modules of three of our courses with a 44% discount for you.

Here are what to expect in each course.

  • 10+ in-depth modules

  • 50+ in-depth chapters

  • 160+ high-quality lessons

  • 48+ hours of video training content

Note that the discounted prices are going up every month as we add new modules.

Also, you can pick up a single course from a collection of courses we have on the MB Platform.

Now, back to the business of today.

The Daily Newsletter for Intellectually Curious Readers

  • We scour 100+ sources daily

  • Read by CEOs, scientists, business owners and more

  • 3.5 million subscribers

In this episode, I will explain Design Patterns, their types, the GoF design patterns, drawbacks, and benefits for backend engineers.

This is coming from my new Vue.js book I’m writing on “Vue Design Patterns”. However, I’m only transferring the knowledge to backend engineers in this series.

Let’s start with the obvious questions for those who just like to know (over and over again)

What are Design Patterns?

Design patterns are reusable solutions to common problems that software developers encounter during application design and development. They serve as templates that can be adapted to solve specific design challenges, offering a standardized way to build software that is maintainable, scalable, and efficient.

In backend development, design patterns provide a framework for structuring your code, ensuring that it is both modular and robust. They are not about reinventing the wheel but about applying established practices that have been proven to work in numerous scenarios.

That’s all there’s about Design Patterns. They are not frameworks, languages, or tools. They are simply patterns or ways you could write or structure your code based on what has been proven to work over time.

As prerequisites, as we progress in this Design Pattern series, you must know Object Oriented Programming very well because Design Patterns seem to favor OOP more. Though the patterns are adapted to any style of coding I will be using OOP concepts.

Also, my code snippet may be in Node.js or Java depending on which I’m comfortable with. However, I will try to make it language-agnostic to help you adapt it to your programming language.

With that out. Let’s start with the types of Design Patterns

Types of Design Patterns

Design patterns can be broadly classified into three categories:

Creational Patterns

These patterns deal with object-creation mechanisms. They abstract the instantiation process, making the system independent of how its objects are created, composed, and represented.

There are five well-known design patterns possible to implement in a wide scope of programming languages:

  1. Singleton

  2. Factory Method

  3. Abstract Factory

  4. Builder

  5. Prototype

Structural Patterns

These patterns concern the composition of classes or objects. They help ensure that parts of a system can be made independent, yet work together as a cohesive whole.

  1. Adapter

  2. Composite

  3. Proxy

  4. Flyweight

  5. Facade

  6. Bridge

  7. Decorator

Behavioral Patterns

These patterns focus on communication between objects, defining the manner and flow of control between them.

  1. Observer Pattern

  2. Strategy Pattern

  3. Command Pattern

  4. Chain of Responsibility Pattern

  5. State Pattern

  6. Mediator Pattern

  7. Iterator Pattern

  8. Visitor Pattern

  9. Template Method Pattern

  10. Interpreter Pattern

  11. Memento Pattern

What is Gangs of Four (GoF)?

The term "Gang of Four" (GoF) refers to the four authors of the influential book "Design Patterns: Elements of Reusable Object-Oriented Software." The GoF categorized 23 design patterns into the three types mentioned above. These patterns have become the cornerstone of object-oriented design and are widely used in software development.

Now, let’s explore the first Design Pattern that everyone should know which is under Creational Design Pattern.

Singleton

It ensures a class has only one instance and provides a global point of access to it. The singleton pattern restricts the initialization of a class to ensure that only one instance of the class can be created.

The Singleton pattern is one of the simplest and most commonly used design patterns in software development.

Here are some use cases of the singleton design patterns:

  • Database connections

  • Logging instances in Node.js applications.

  • Creating a new object

  • Connecting to mail servers

Let's break down a simple implementation of the Singleton pattern in JavaScript, line by line.

class Singleton {
 let instance;
    constructor() {
        if (!Singleton.instance) {
            Singleton.instance = this;
        }
        return Singleton.instance;
    }
}

const instance1 = new Singleton();
const instance2 = new Singleton();

console.log(instance1.value === instance2.value); // true

Below is a line-by-line explanation of the Singleton Design Pattern. First, we create a local or private variable called instance.

1. class Singleton {:

This line defines a new class called Singleton. In JavaScript, classes are templates for creating objects, and they encapsulate data with methods.

2. constructor() {:

The constructor is a special method in a class that gets called when a new instance of the class is created. It's typically used to initialize the object's properties.

3. if (!Singleton.instance) {:

This conditional checks whether the Singleton.instance property has already been defined. If it hasn't (meaning this is the first time the class is being instantiated), the code inside the if block will execute. This is crucial for ensuring that only one instance of the class is ever created.

4. this.value = Math.random(100);:

If the condition in the previous line is true, the value property of the instance is assigned a random number between 0 and 1 (since Math.random() generates a float between 0 and 1). This value will be used to demonstrate that multiple instances of the Singleton class share the same value.

5. Singleton.instance = this;:

Here, the Singleton.instance property is assigned the current instance of the class (this). This ensures that the next time an instance of the Singleton class is created, the previously created instance will be returned instead of creating a new one.

7. return Singleton.instance;:

The constructor method returns the instance of the class stored in Singleton.instance. This means that every time you create a new instance of the Singleton class, you're getting the same instance.

9. const instance1 = new Singleton();:

This line creates the first instance of the Singleton class. Since it's the first instance, the constructor will execute its logic and store the instance in Singleton.instance.

10. const instance2 = new Singleton();:

Here, a second instance of the Singleton class is created. However, due to the Singleton pattern, the constructor will return the already existing instance stored in Singleton.instance, rather than creating a new one.

11. console.log(instance1.value === instance2.value); // true:

Finally, this line checks whether the value property of instance1 is equal to the value property of instance2. Since both instance1 and instance2 reference the same Singleton instance, the values are identical, and the comparison returns true.

Summary

  • Single Instance: The Singleton pattern ensures that a class has only one instance. Any subsequent attempts to create a new instance will return the existing one.

  • Global Access Point: The pattern provides a global point of access to the instance, which can be particularly useful in managing shared resources like database connections or configuration settings.

  • Use Case Consideration: While the Singleton pattern is powerful, it should be used judiciously. Overusing it can lead to tightly coupled code, making it harder to maintain and test.

This example demonstrates how the Singleton pattern works in JavaScript, specifically using Node.js. Understanding this pattern is essential for backend engineers as it provides a way to manage shared resources efficiently and consistently across an application.

That will be all for this week. I like to keep this newsletter short.

Today, I discussed Design Patterns, their types, the GoF design patterns, drawbacks, and benefits for backend engineers.

Next week, I will start exploring the Factory Method.

Don’t miss it. Share with a friend

Did you learn any new things from this newsletter this week? Please reply to this email and let me know. Feedback like this encourages me to keep going.

See you on Next Week.

Remember to start learning backend engineering from our courses:

Top 5 Remote Backend Jobs this week

Here are the top 5 Backend Jobs you can apply to now.

👨‍💻 Docplanner
✍️ Backend Engineer
đź“ŤRemote, Poland
đź’° Click on Apply for salary details
Click here to Apply for this role.

👨‍💻 Spotify
✍️ Backend Engineer II, Music
đź“ŤRemote, United Kingdom
đź’° Click on Apply for salary details
Click here to Apply for this role.

👨‍💻 HashiCorp
✍️ Backend Engineer, Boundary Transparent Session (hybrid)
đź“ŤRemote, India
đź’° Click on Apply for salary details
Click here to Apply for this role.

👨‍💻Sportradar
✍️ Backend Engineer
đź“ŤRemote
đź’° Click on Apply for salary details
Click here to Apply for this role.

Want more Remote Backend Jobs? Visit GetBackendJobs.com

Backend Engineering Resources

Whenever you're ready

There are 4 ways I can help you become a great backend engineer:

1. The MB Platform: Join 1000+ backend engineers learning backend engineering on the MB platform. Build real-world backend projects, track your learnings and set schedules, learn from expert-vetted courses and roadmaps, and solve backend engineering tasks, exercises, and challenges.

2. ​The MB Academy:​ The “MB Academy” is a 6-month intensive Advanced Backend Engineering BootCamp to produce great backend engineers.

3. MB Video-Based Courses: Join 1000+ backend engineers who learn from our meticulously crafted courses designed to empower you with the knowledge and skills you need to excel in backend development.

4. GetBackendJobs: Access 1000+ tailored backend engineering jobs, manage and track all your job applications, create a job streak, and never miss applying. Lastly, you can hire backend engineers anywhere in the world.

LAST WORD đź‘‹ 

How am I doing?

I love hearing from readers, and I'm always looking for feedback. How am I doing with The Backend Weekly? Is there anything you'd like to see more or less of? Which aspects of the newsletter do you enjoy the most?

Hit reply and say hello - I'd love to hear from you!

Stay awesome,
Solomon

I moved my newsletter from Substack to Beehiiv, and it's been an amazing journey. Start yours here.

Reply

or to participate.