Factory-Pattern | Javascript Design Pattern Simplified | Part 2
Tags: webdev, javascript, programming, tutorial
Published: 2024-07-02 08:55:00

As a developer, understanding various JavaScript design patterns is crucial for writing maintainable, efficient, and scalable code. Here are some essential JavaScript design patterns that you should know:

## Factory Pattern 

The Factory pattern provides a way to create objects without specifying the exact class of the object that will be created.

**Example**

`class Car {
  constructor(model) {
    this.model = model;
  }
}

class CarFactory {
  static createCar(model) {
    return new Car(model);
  }
}

const car1 = CarFactory.createCar('Tesla Model S');
const car2 = CarFactory.createCar('BMW i8');`

## Real World Example


###Example: User Account Creation


***Real-World Scenario:*** A system may need to create different types of user accounts (e.g., Admin, Guest, RegisteredUser). The Factory pattern provides a way to create these objects without specifying the exact class.

**Define User Classes:**

```
class Admin {
  constructor(name) {
    this.name = name;
    this.role = 'Admin';
  }
}

class Guest {
  constructor(name) {
    this.name = name;
    this.role = 'Guest';
  }
}

class RegisteredUser {
  constructor(name) {
    this.name = name;
    this.role = 'RegisteredUser';
  }
}
```

**Create the Factory Class:**

```
class UserFactory {
  static createUser(type, name) {
    switch (type) {
      case 'admin':
        return new Admin(name);
      case 'guest':
        return new Guest(name);
      case 'registered':
        return new RegisteredUser(name);
      default:
        throw new Error('Unknown user type');
    }
  }
}
```

**Use the Factory Class:**

```
const admin = UserFactory.createUser('admin', 'Alice');
const guest = UserFactory.createUser('guest', 'Bob');

console.log(admin); // Admin { name: 'Alice', role: 'Admin' }
console.log(guest); // Guest { name: 'Bob', role: 'Guest' }
```

## Use Cases of the Factory Pattern 


### 1.Pattern Object Creation with Varying Complexities


***Use Case:*** When the creation process of an object is complex or requires multiple steps, the Factory pattern can encapsulate the creation logic.

**Example:** Creating different types of documents (e.g., PDFs, Word documents, spreadsheets) where each type has a distinct creation process.

### 2.Switching Between Related Objects Dynamically

**Use Case:** When the application needs to switch between related objects at runtime without modifying the existing code, the Factory pattern allows for dynamic object creation.

**Example:** A notification system that sends alerts via different channels (e.g., email, SMS, push notifications) based on user preferences or system state.


### Conclusion

Understanding these design patterns and knowing when to apply them can greatly improve your coding skills and make you a more effective full-stack developer. They help in creating robust and maintainable code.

Mastering these patterns will help you build better software.

Happy Coding! 🧑‍💻

**Connect with Me 🙋🏻: [LinkedIn](https://www.linkedin.com/in/aakash-kumar-182a11262?utm_source=share&utm_campaign=share_via&utm_content=profile&utm_medium=android_app)**