Example of Factory Method in JavaScript Design Pattern
Below is an example of the Factory Method in JavaScript Design Pattern:
Javascript
// Factory function to create a user based on role and user info const createUser = (role, userInfo) => { // Initialize a user object with common properties const user = { name: userInfo.name, password: userInfo.password }; // Define specific additional information based on the role const specificInfo = { admin: () => ({ role: 'Admin' , key: userInfo.key }), customer: () => ({ role: 'Customer' , address: userInfo.address }), seller: () => ({ role: 'Seller' , shopAddress: userInfo.shopAddress, contact_No: userInfo.contact_No }) }; // Get additional information based on the role provided const additionalInfo = specificInfo[role] ? specificInfo[role]() : null ; // If an invalid role was specified, throw an error if (!additionalInfo) { throw new Error( 'Invalid role specified.' ); } // Combine the common user properties with additional role-specific properties return { ...user, ...additionalInfo }; }; // Create an Admin User instance const adminUser = createUser( 'admin' , { name: 'Abhishek' , password: 'Abhi1233' , key: '#1244534-fadsv34' }); // Create a Customer User instance const customerUser = createUser( 'customer' , { name: 'John Doe' , password: 'Password123' , address: '123 Main St' }); // Create a Seller User instance const sellerUser = createUser( 'seller' , { name: 'Jane Smith' , password: 'SellerPass' , shopAddress: '456 Market St' , contact_No: '123-456-7890' }); // Log the Admin User details console.log( 'Admin User:' , adminUser); // Log the Customer User details console.log( 'Customer User:' , customerUser); // Log the Seller User details console.log( 'Seller User:' , sellerUser); |
Output:
Admin User: {
name: ‘Abhishek’
password: ‘Abhi1233’,
role: ‘Admin’,
key: ‘#1244534-fadsv34’}
Customer User: {
name: ‘John Doe’,
password: ‘Password123’,
role: ‘Customer’,
address: ‘123 Main St’}
Seller User: {
name: ‘Jane Smith’,
password: ‘SellerPass’,
role: ‘Seller’,
shopAddress: ‘456 Market St’,
contact_No: ‘123-456-7890’}
Explanation:
const createUser = (role, userInfo) => {
const user = {
name: userInfo.name,
password: userInfo.password};
Here, we have a function createUser this function is called factory function.
It takes two parameters:
- Role (representing the user role, e.g., ‘admin’, ‘customer’, ‘seller’)
- UserInfo (an object containing user-specific information like name, password, etc.).
Inside this function, we start by creating a user object with common properties, name and password, taken from the userInfo object.
const specificInfo = {
admin: () => ({ role: ‘Admin’, key: userInfo.key }),
customer: () => ({ role: ‘Customer’, address: userInfo.address }),
seller: () => ({ role: ‘Seller’, shopAddress: userInfo.shopAddress, contact_No: userInfo.contact_No })
};
Here we define a specificInfo object. It serves as a lookup table where each role (admin, customer, or seller) is associated with a function. These functions return an object with role-specific information based on the provided userInfo.
- For the ‘admin’ role, the function returns an object with a role of ‘Admin’ and includes a ‘key’ based on the provided userInfo.
- For the ‘customer’ role, the function returns an object with a role of ‘Customer’ and includes an ‘address’ based on the provided userInfo.
- For the ‘seller’ role, the function returns an object with a role of ‘Seller’ and includes ‘shopAddress’ and ‘contact_No’ based on the provided userInfo.
This structure allows for role-specific handling of user information, ensuring that each user type (admin, customer, or seller) gets the appropriate properties set based on their role.
const additionalInfo = specificInfo[role] ? specificInfo[role]() : null;
Here, we use the role parameter to retrieve the corresponding function from the specificInfo object. If the role is valid, we call the corresponding function to get the additional role-specific information. If the role is invalid, it returns null.
if (!additionalInfo) {
throw new Error(‘Invalid role specified.’);
}
Here, we check if additionalInfo is null. If it’s null, we throw an error using throw new Error().
return { …user, …additionalInfo };
Finally, if the role is valid, we combine the common user properties (name and password) with the additional role-specific properties using the spread operator
({ …user, …additionalInfo }).
This creates a new object that represents the user with all the appropriate properties based on the specified role, and we return it.
The createUser function essentially acts as a factory, creating a user object based on the provided role and user information.
const adminUser = createUser(‘admin’, {
name: ‘Abhishek’,
password: ‘Abhi1233’,
key: ‘#1244534-fadsv34’});
const customerUser = createUser(‘customer’, {
name: ‘John Doe’,
password: ‘Password123’,
address: ‘123 Main St’});
const sellerUser = createUser(‘seller’, {
name: ‘Jane Smith’,
password: ‘SellerPass’,
shopAddress: ‘456 Market St’,
contact_No: ‘123-456-7890’});
using createUser function to create different type of user according to there role.
console.log(‘Admin User:’, adminUser);
console.log(‘Customer User:’, customerUser);
console.log(‘Seller User:’, sellerUser);
The user information for each type is logged to the console.
Factory Method in JavaScript | Design Pattern
The Factory Design Pattern is a creational pattern that allows for the creation of objects without exposing the creation logic to the client. It involves creating a separate factory function that is responsible for creating instances of various related objects based on a specified input. In modern software development, the Factory Design Pattern plays a crucial role in creating objects while abstracting away the specifics of their creation. In JavaScript, we can implement this pattern using factory functions.
Important Topics of Factory Method in Javascript Design Pattern
- Example of Factory Method in JavaScript Design Pattern
- Advantages of Factory Method in JavaScript Design Pattern
- Disadvantages of Factory Method in JavaScript Design Pattern