1. The factory pattern abstracts the process of creating specific objects, but classes cannot be created in ECMAScript, so a function is used to encapsulate the details of creating objects with a specific interface. Take the following situation as an example.
There is an employee category, with name, age, position attributes,
Use the above method to define two employees, Jim, Sun
var Jim = CreateEmployee("jim", 22, "SoftWare Engineer");
var Sun = CreateEmployee("Sun",24,"Doctor");
Then use the SayName method separately to get the two employees to sign up
();
();
The function CreateEmployee can construct an Employee object containing the necessary information based on the parameters, and this function can be called infinitely. Although the factory pattern solves the problem of creating multiple similar objects, it does not solve the problem of how to know an object type.
There is an employee category, with name, age, position attributes,
Copy the codeThe code is as follows:
function CreateEmployee(name, age, job) {
var Emp = new Object();
= name;
= age;
= job;
= function () {
alert();
};
return Emp;
}
var Emp = new Object();
= name;
= age;
= job;
= function () {
alert();
};
return Emp;
}
Use the above method to define two employees, Jim, Sun
Copy the codeThe code is as follows:
var Jim = CreateEmployee("jim", 22, "SoftWare Engineer");
var Sun = CreateEmployee("Sun",24,"Doctor");
Then use the SayName method separately to get the two employees to sign up
Copy the codeThe code is as follows:
();
();
The function CreateEmployee can construct an Employee object containing the necessary information based on the parameters, and this function can be called infinitely. Although the factory pattern solves the problem of creating multiple similar objects, it does not solve the problem of how to know an object type.