Continue to document a few javascript design patterns, and have time to refine them later to form a whole.

The factory pattern

An abstract Factory creates objects that are related to some common topic. In object-oriented programming, a Factory is an object that creates other objects. An abstract Factory creates a common topic that is shared by the objects it creates.

You might wonder why you leave the object creation process to Factory rather than just new the constructor. The reason is that the new constructor has limited control over the creation process, and sometimes you need to give control of object creation to Factory, which has more extensive capabilities.

Capabilities here may include scenarios where the creation process involves object caching, object sharing or reuse, other complex logic, and objects that different devices interact with. If your application needs more control over the object creation process, consider using Factory.

The illustration

The role of

The following characters participate in this mode:

  • AbstractFactoryAbstract factory: used to declare a createproductInterface, which is not normally used in javascript.
  • ConcreteFactory: Figurative factory, manufacturingproductFactory object whose create method returns oneproductObject in the sample codeEmployeeFactoryandVendorFactoryIt’s a figurative factory.
  • Products: Product object, byfactoryThe product object created in the sample codeEmployeeandVendorThat’s the product object.
  • AbstractProduct: AbstractProduct, used to declare the interface to create the product, not used in javascript.

For example,

In the following example, there are two concrete projects, EmployeeFactory and VendorFactory, with the first creating an Employee instance and the second creating a Vendor instance. Create an array of two Employees and two vendors and ask them to state their roles and names.

function Employee(name) { this.name = name; this.say = function () { console.log("I am employee " + name); }; } function EmployeeFactory() { this.create = function (name) { return new Employee(name); }; } function Vendor(name) { this.name = name; this.say = function () { console.log("I am vendor " + name); }; } function VendorFactory() { this.create = function (name) { return new Vendor(name); }; } function run() { var persons = []; var employeeFactory = new EmployeeFactory(); var vendorFactory = new VendorFactory(); persons.push(employeeFactory.create("Joan DiSilva")); persons.push(employeeFactory.create("Tim O'Neill")); persons.push(vendorFactory.create("Gerald Watson")); persons.push(vendorFactory.create("Nicole McNight")); for (var i = 0, len = persons.length; i < len; i++) { persons[i].say(); }}Copy the code