js之单例模式

匿名 (未验证) 提交于 2019-12-02 21:53:52

单例模式是指一个类,只有一个实例。实现的思路是,创建实例时候加判断,如果有实例则返回,如果没有就new一个,并返回。

第一步: 创建类。

function Waiter(id, name, salary) { // 创建了一个Waiter类         Employees.call(this, id, name, salary) // 这里Waiter继承了Employees,Employees是个父类,也可以没有}     Waiter.prototype = Object.create(Employees.prototype);     Waiter.prototype.constructor= Waiter;     Waiter.prototype.work = function (arg) { // 重写原型上的方法         if (arg instanceof Array){ //数组的话,记录点菜             console.log('finish order dish $记录work');             return this;         } else { //上菜行为             console.log('finish serving a dish $记录work')         }     };     // cook调用的方法,返回菜单     Waiter.prototype.tellCookTheMenu = function () {         return this.menu;     };     // cook调用的方法,拿到做好的菜     Waiter.prototype.serving = function () {         this.work();// 上菜行为         this.customer.eat();     };

第二步:使用return结果,这里有判断。

 return {         name: 'waiter',         getWaiterInstance: function (...arg) {             if (!waiter) {                 waiter = new Waiter(...arg)             }             return waiter;         }     }

第三部:将1、2整合

//服务员 单例 var waiterSingle = (function () { // 是一个立即执行函数,并将执行的结果赋值给waiterSingle     var waiter = null; // 实例存在这个变量里     function Waiter(id, name, salary) {         Employees.call(this, id, name, salary)     }     Waiter.prototype = Object.create(Employees.prototype);     Waiter.prototype.constructor= Waiter;     Waiter.prototype.work = function (arg) { // 重写原型上的方法         if (arg instanceof Array){ //数组的话,记录点菜             console.log('finish order dish $记录work');             return this;         } else { //上菜行为             console.log('finish serving a dish $记录work')         }     };     // cook调用的方法,返回菜单     Waiter.prototype.tellCookTheMenu = function () {         return this.menu;     };     // cook调用的方法,拿到做好的菜     Waiter.prototype.serving = function () {         this.work();// 上菜行为         this.customer.eat();     };      // 从顾客order方法,拿到点的菜     Waiter.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) {  // 判断如果waiter里没有,则new,并赋值给waiter                 waiter = new Waiter(...arg)             }             return waiter;         }     } })();

第四步:创建实例方式

var waiter = waiterSingle.getWaiterInstance(2, 'Lucy', 5000);

文章来源: js之单例模式
标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!