Singleton mode refers to a class, with only one instance. The idea of implementation is to add judgment when creating an instance, and if there are instances then return if there is no new one and return. First step: Create a class.
function Waiter (ID, name, salary) { //created a waiter class Employees.call ( This, ID, name, salary)//Here waiter inherited the Employees,employees is a parent class, can also not
} Waiter.prototype=object.create (Employees.prototype); Waiter.prototype.constructor=Waiter; Waiter.prototype.work= function (ARG) {//overriding a method on a prototype if(Arg instanceof Array) {//An array of words, record a la carteConsole.log ('Finish order dish $ record work'); return This; } Else{//Serving BehaviorConsole.log ('finish serving a dish $ record work') } }; //Cook calls the method that returns the menuWaiter.prototype.tellCookTheMenu =function () {return This. menu; }; //Cook called the method to get a good dishWaiter.prototype.serving =function () { This. work ();//Serving Behavior This. Customer.eat (); };
Step two: Use the return result, here is the judgment.
return { ' waiter ', function (... arg) {if (! Waiter) { new Waiter (... arg) } return waiter;} }
Part III: Integration of 1 and 2
//Waiter Single CasevarWaitersingle = (function() { //is an immediate execution function and assigns the result of execution to Waitersingle varWaiter =NULL;//instance exists in this variable functionWaiter (ID, name, salary) {Employees.call ( This, ID, name, salary)} Waiter.prototype=object.create (Employees.prototype); Waiter.prototype.constructor=Waiter; Waiter.prototype.work=function(ARG) {//overriding a method on a prototype if(ARGinstanceofArray) {//An array of words, record a la carteConsole.log (' Finish order dish $ record work '); return This; } Else{//Serving BehaviorConsole.log (' Finish serving a dish $ record work ') } }; //Cook calls the method that returns the menuWaiter.prototype.tellCookTheMenu =function () { return This. menu; }; //Cook called the method to get a good dishWaiter.prototype.serving =function () { This. work ();//Serving Behavior This. Customer.eat (); }; //from the customer order method, get the order of the dishesWaiter.prototype.getMenu =function(ARG) { This. Customer =Arg; This. Menu =Arg.dish; Console.log (' Waiter get the menu ', This. menu); return This; }; return{name:' Waiter ', Getwaiterinstance:function(... Arg) {if(!waiter) {//judge if there is no waiter, then new, and assign to waiterWaiter =NewWaiter (.... Arg)}returnWaiter; } }})();
Fourth Step: Create instance Mode
var waiter = waitersingle.getwaiterinstance (2, ' Lucy ', 5000);
A single example of JS mode