DEV Community

loading...
Cover image for Master Design Patterns By Building Real Projects - Factory Pattern - Javascript

Master Design Patterns By Building Real Projects - Factory Pattern - Javascript

hieptl profile image Hiep Le Updated on ・3 min read

Creational Pattern - Factory Pattern.

This is the fourth part in my series (23 GoF Design Patterns). My series will help you understand about design patterns by building real projects. For this reason, you can see the places in which each pattern could be applied. I want to focus on learning by doing instead of talking too much about theories.

I'm Hiep. I work as a full-time software engineer. Most of my open-source projects are focused on one thing - to help people learn 📚.

I created a git repository that help you understand about design patterns by building real projects.

Github link:

https://github.com/hieptl/javascript-dessign-patterns

If the repository is useful, please help me share the post and give me a Github's star. It will make me feel motivation to work even harder. I will try to make many open sources and share to the community ❤️.

I also created some series that help you improve your practical skills ❤️

1. Learn React By Building Netflix

https://dev.to/hieptl/learn-react-by-building-netflix-1127

Table of Contents

1. Definition.

Factory pattern defines an interface for creating a single object, but let subclasses decide which class to instantiate. Factory Method lets a class defer instantiation to subclasses.

2. Scenarios.

We can imagine that we want to build an ecommerce website for Apple. When the users visit our website and input product's names, we should return Apple's products based on input names.

Example: Henry visits our website, he inputs 'Iphone12', our website should return the information of Iphone12 to him. In the second time, he inputs 'Ipad Pro 2021', our website should return the information of 'Ipad Pro 2021'.

In fact, our website will return the objects based on input names. It sounds like the definition of factory pattern. We will build the system by applying factory pattern.

3. Building a Ecommerce Website for Apple.

I want to use Javascript class to implement the idea because in the case you are using object-oriented programming languages or you have to use those languages in the future, you can still implement design patterns by using different languages. In my opinion, design patterns are mindset and approaches and not depend on programming languages.

Step 1: Create AppleProduct class to store the information of Apple's products.

class AppleProduct {
  constructor(name, price, description) {
    this.name = name;
    this.price = price;
    this.description = description;
  }
}
Enter fullscreen mode Exit fullscreen mode

Step 2: Create AppleProductFactory class to return Apple's product based on input names.

class AppleProductFactory {
  static create(name) {
    switch(name) {
      case 'Iphone 12':
        return new AppleProduct(name, 2000, 'This is Iphone 12');
      case 'Ipad Pro 2021':
        return new AppleProduct(name, 2000, 'This is Ipad Pro 2021');
      default:
        return null;  
    }
  }
}
Enter fullscreen mode Exit fullscreen mode

We define the create method as static because static method can be accessed directly by using the class's name.

Example: We can write

 AppleProductFactory.create('Iphone 12');

Instead of

 const appleProductFactory = new AppleProductFactory();
 appleProductFactory.create('Iphone 12');

Our full source code will look like this:

class AppleProduct {
  constructor(name, price, description) {
    this.name = name;
    this.price = price;
    this.description = description;
  }
}

class AppleProductFactory {
  static create(name) {
    switch(name) {
      case 'Iphone 12':
        return new AppleProduct(name, 2000, 'This is Iphone 12');
      case 'Ipad Pro 2021':
        return new AppleProduct(name, 2000, 'This is Ipad Pro 2021');
      default:
        return null;  
    }
  }
}

const firstProduct = AppleProductFactory.create('Iphone 12');
const secondProduct = AppleProductFactory.create('Ipad Pro 2021');

console.log(firstProduct);
console.log(secondProduct);
Enter fullscreen mode Exit fullscreen mode

4. Result.

AppleProduct {
  name: 'Iphone 12',
  price: 2000,
  description: 'This is Iphone 12'
}
AppleProduct {
  name: 'Ipad Pro 2021',
  price: 2000,
  description: 'This is Ipad Pro 2021'
}
Enter fullscreen mode Exit fullscreen mode

The above result describes that our AppleProductFactory return the information of products based on input names. Factory pattern helps us hide the logic of constructing objects.

By using design patterns, we can understand the core concepts and make our code become more readable and cleaner. I hope that the post can help you understand about Factory pattern.

Thanks and Best Regards,
Hiep.

Discussion (2)

Collapse
ingjorgevasquez profile image
Jorge Vasquez

Hi Hiep, I hope you're doing well. Good explanation of the pattern 👍. However, I have a concern with this implementation, related to the very specific names we can handle in the switch statement, I mean, if a customer would had used a different combination of capital letters, their search wouldn't had matched anything.
Do you know an elegant solution that allows our application to recognize different ways of writing a product names and match the desired product?

Collapse
hieptl profile image
Hiep Le Author

Hi @ingjorgevasquez ,

Thank you for your question ❤️. The purpose of my post is to help the developers understand about the concept of Factory pattern. We are talking about how to make the search feature become better. It may be another topic 😄

From my point of view, it depends on your business and the number of users who are using the system and what kinds of searching that we want to support. I am the person who take care about the requirements and business first before choosing the technical solutions for the application.

If we are building a start-up, it is totally fine to search the results in the relational database because we want to test the reactions of the market with our product.

On the other hand, if our product is scaling up and we do not care too much about the exactness of the results so we can use full text search solution. There are different technologies that support full text search such as Elastic Search, Lucence, ...

Thanks and Best Regards,
Hiep

Forem Open with the Forem app