[JS Design Pattern Notes] Magical Magician - Simple Factory Pattern (Creative)

Simple Factory: Also known as static factory method, a factory object decides to create an instance of a certain product object class. Mainly used to create objects of the same class.

first demand

To develop a login module, if the input content of the user name input box does not meet the specifications, a warning box will be customized to warn: 'The user name cannot be more than 16 letters or numbers'

var LoginAlert = function(text) {
	this.content = text;
}
LoginAlert.prototype.show = function() {
	// show alert box
}

var useNameAlert = new LoginAlert('Username cannot be more than 16 letters or numbers');
useNameAlert.show();

There is also a prompt about the user password input error: 'The entered password is incorrect'.

var passwordAlert = new LoginAlert('The entered password is incorrect');
passwordAlert.show();

There is another requirement. When the user logs in, if the user name does not exist, it will also prompt: 'Your user name does not exist, please re-enter'.

This time you have to recreate a class.

var LoginConfirm = function(text) {
	this.content = text;
}
LoginConfirm.prototype.show = function() {
	// Show confirmation box
}

var loginFailConfirm = new LoginConfirm('Your username does not exist, please re-enter');
loginFailConfirm.show();

Now, after the login is successful, a custom prompt box is needed. In addition to the cancel button, it also prompts a sentence: 'Welcome back'.

Here's another new class:

var LoginPrompt = function(text) {
	this.content = text;
}
LoginPrompt.prototype.show = function() {
	// Show tooltip
}

Now we need to develop a registration module to use the functions related to the prompt box. ’

If there are too many classes, provide a

The previous login module had three classes, namely LoginAlert, LoginConfirm, LoginPrompt, or prefixed with Login. Now let's write a simple factory, which is to encapsulate a function. We can use this function to create the objects we need for my use. . This way, other people don't have to care about which base classes are used to create this object, so other people just need to remember this function. This function is also commonly referred to as a factory function.

For example, such as a magician who can do magic, you want the magician to give you a gift, but you don't care what the magician uses to change, you only need the magician.

For example, a sports store sells sports equipment, which contains a lot of sports goods and related introductions. When you need to buy a basketball, you only need to tell the salesperson, and he will help you find what you want.

// Basketball base class
var Basketball = function() {
	this.intro = 'Basketball is popular in America';
}
Basketball.prototype = {
	getMember: function() {
		console.log('Each team needs 5 players');
	},
	getBallSize: function() {
		console.log('basketball is big');
	}
}

// Football base class
var Football = function() {
	this.intro = 'football is popular';
}
Football.prototype = {
	getMember: function() {
		console.log('Each team needs 11 players');
	},
	getBallSize: function() {
		console.log('football is big')
	}
}

// Tennis base class
var Tennis = function() {
	this.intro = 'Introduction to Tennis';
}
Tennis.prototype = {
	getMember: function() {
		console.log('Each team needs 1 player')
	},
	getBallSize: function() {
		console.log('very little tennis');
	}
}

// sports factory
var sportsFactory = function(name) {
	switch(name) {
		case 'NBA':
			return new Basketball();
		case 'worldcup':
			return new Football();
		case 'frenchopen':
			return new Tennis();
	}
}

// Example
var footBall = sportsFactory('worldcup');
console.log(footBall);
console.log(footBall.intro);
footBall.getMember();

Then the custom popup can be implemented like this:

var popFactory = function(name,text) {
	switch(name) {
		case 'alert':
			return new LoginAlert(text);
		case 'confirm':
			return new LoginConfirm(text);
		case 'prompt':
			return new LoginConfirm(text);
	}
}
var useNameAlert = popFactory('alert','Username cannot be more than 16 letters or numbers');
useNameAlert.show()

An object can sometimes replace many classes

From the above three classes, LoginAlert, LoginConfirm, and LoginConfirm, there are many similarities, such as closing buttons, prompt copy, etc. We can also abstract and extract the common ones, or we can implement them in a simple factory way.

For example, let's say I want to create some books, and those books have some similarities, such as table of contents, page numbers, etc. There are also some dissimilarities, such as the title of the book, the time of publication, the type of the book, etc. It is easy to deal with the similar attributes of the created objects, and it is necessary to deal with different attributes in a targeted manner. For example, we use different attributes as Parameters are passed in for processing.

// factory pattern
function createBook(name,time,type) {
	// Create an object and extend properties and methods on the object
	var o = new Object();
	o.name = name;
	o.time = time;
	o.type = type;
	o.getName = function() {
		console.log(this.name)
	}
	
	// return the object
	return o;
}

var book1 = createBook('js book','2004','js');
var book2 = createBook('java book','2005','java');

book1.getName(); // js book
book2.getName(); // java book

We optimize the above three bullet box classes:

function createPop(type,text) {
	// Create an object and extend properties and methods on the object
	var o = new Object();
	o.content = text;
	o.show = function() {
		// display method
	}
	if(type == 'alert') {
		// Alert Box Differences
	}
	if(type == 'prompt') {
		// Toolbox Differences Section
	}
	if(type == 'confirm') {
		// Check Box Differences Section
	}
	
	// return the object
	return o;
}

// Create alert boxes
var userNameAlert = createPop('alert','Username can only be 26 letters or numbers');

Your understanding determines your choice

The first is created by instantiating objects from a class, and the second is achieved by creating new objects and then wrapping them to enhance their properties and functionality.

Posted by johnathanhebert on Tue, 11 Oct 2022 18:06:45 +0300