JavaScript设计模式有哪些及怎么实现

本文小编为大家详细介绍“JavaScript设计模式有哪些及怎么实现”,内容详细,步骤清晰,细节处理妥当,希望这篇“JavaScript设计模式有哪些及怎么实现”文章能帮助大家解决疑惑,下面跟着小编的思路慢慢深入,一起来学习新知识吧。

1.构造器设计模式。

这是一种特殊的方法,用于在分配内存后初始化新创建的对象。由于 JavaScript 通常是面向对象的,它最常处理对象,因此我打算深入研究对象构造函数。在JavaScript中可以通过三种方式创建新对象:

以下是创建构造函数设计模式的一种方法。

// This creates a new empty Objectvar newObject = {};// This creates a new empty Objectvar newObject = Object.create(Object.prototype);var newObject = newObject();

要访问函数的属性,您需要初始化对象。

const object = new ConstructorObject();

因此,上面的 new 关键字告诉 JavaScript aconstructorObject应该充当构造函数。继承是这种设计模式不支持的一件事。在此处了解更多详细信息。

2.原型模式

原型模式基于原型继承,由此创建的对象充当其他对象的原型。实际上,原型充当创建的每个对象构造函数的蓝图。

例子

var myCar= {name:"Ford",brake:function(){console.log("Stop! I am applying brakes");
}
Panic : function (){console.log ( "wait. how do you stop thuis thing?")
}
}// use objec create to instansiate a new carvar yourCar= object.create(myCar);//You can now see that one is a prototype of the otherconsole.log (yourCar.name);]

3.模块设计模式

在模块设计模式中,对原型模式进行了改进。模块模式中设置了不同类型的修饰符(私有和公共)。您可以在没有冲突的情况下创建类似的函数或属性。公开重命名函数具有灵活性。令人生畏的部分是无法从外部环境覆盖创建的函数。

例子

function AnimalContainter () {const container = [];function addAnimal (name) {
container.push(name);
}function getAllAnimals() {return container;
}function removeAnimal(name) {const index = container.indexOf(name);if(index < 1) {throw new Error('Animal not found in container');
}
container.splice(index, 1)
}return {add: addAnimal,get: getAllAnimals,remove: removeAnimal
}
}const container = AnimalContainter();
container.add('Hen');
container.add('Goat');
container.add('Sheep');console.log(container.get()) //Array(3) ["Hen", "Goat", "Sheep"]container.remove('Sheep')console.log(container.get()); //Array(2) ["Hen", "Goat"]

4.单例模式

在只需要创建一个实例的场景中是必不可少的,例如一个数据库连接。只能在连接关闭时创建实例,或者确保在打开新实例之前关闭打开的实例。这种模式也被称为严格模式,与这种模式相关的一个缺点是它在测试中的艰巨体验,因为它隐藏的依赖对象不容易被挑出来进行测试。

例子

function DatabaseConnection () {let databaseInstance = null;// tracks the number of instances created at a certain timelet count = 0;function init() {console.log(`Opening database #${count + 1}`);//now perform operation}function createIntance() {if(databaseInstance == null) {
databaseInstance = init();
}return databaseInstance;
}function closeIntance() {console.log('closing database');
databaseInstance = null;
}return {open: createIntance,close: closeIntance
}
}const database = DatabseConnection();
database.open(); //Open database #1database.open(); //Open database #1database.open(); //Open database #1database.close(); //close database

5.工厂模式。

它是一种创建对象,无需构造函数即可创建对象。它提供了创建对象的通用接口,我们可以在其中指定要创建的工厂对象的类型。因此,我们只指定对象,工厂实例化并返回给我们使用。当对象组件设置具有高度复杂性并且当我们想要根据所处环境轻松创建对象的不同实例时,使用工厂模式是明智的。当处理许多对象时,我们也可以使用工厂模式共享相同属性的小对象以及在组合需要解耦的对象时。

例子

// Dealer ADealerA = {};
DealerA.title = function title() {return "Dealer A";
};
DealerA.pay = function pay(amount) {console.log(`set up configuration using username: ${this.username} and password: ${this.password
}`);return `Payment for service ${amount} is successful using ${this.title()}`;
};//Dealer BDealerB = {};
DealerB.title = function title() {return "Dealer B";
};
DealerB.pay = function pay(amount) {console.log(`set up configuration using username: ${this.username}and password: ${this.password}`);return `Payment for service ${amount} is successful using ${this.title()}`;
};//@param {*} DealerOption//@param {*} configfunction DealerFactory(DealerOption, config = {}) {const dealer = Object.create(dealerOption);Object.assign(dealer, config);return dealer;
}const dealerFactory = DealerFactory(DealerA, {username: "user",password: "pass"});console.log(dealerFactory.title());console.log(dealerFactory.pay(12));const dealerFactory2 = DealerFactory(DealerB, {username: "user2",password: "pass2"});console.log(dealerFactory2.title());console.log(dealerFactory2.pay(50));

6.观察者模式

观察者设计模式在对象与其他对象集同时通信的地方很方便。在这种观察者模式中,没有不必要的跨状态推拉事件,而是涉及的模块只修改数据的当前状态。

例子

function Observer() {this.observerContainer = [];
}
Observer.prototype.subscribe = function (element) {this.observerContainer.push(element);
}// the following removes an element from the containerObserver.prototype.unsubscribe = function (element) {const elementIndex = this.observerContainer.indexOf(element);if (elementIndex &gt; -1) {this.observerContainer.splice(elementIndex, 1);
}
}/**
* we notify elements added to the container by calling
* each subscribed components added to our container
*/Observer.prototype.notifyAll = function (element) {this.observerContainer.forEach(function (observerElement) {
observerElement(element);
});
}

7.命令模式

最后,我想说命令设计模式结束了我对 JavaScript 设计模式的 7 个最佳总结。命令设计模式将方法调用、操作或请求封装到单个对象中,以便我们可以自行决定传递方法调用。命令设计模式让我们有机会从任何执行命令的对象发出命令,并将责任委托给不同的对象。这些命令以run()和execute()格式显示。

(function(){var carManager = {//information requestedrequestInfo: function( model, id ){return "The information for " + model + " with ID " + id + " is foo bar";
},// now purchase the carbuyVehicle: function( model, id ){return "You have successfully purchased Item " + id + ", a " + model;
},// now arrange a viewingarrangeViewing: function( model, id ){return "You have successfully booked a viewing of " + model + " ( " + id + " ) ";
}
};
})();

读到这里,这篇“JavaScript设计模式有哪些及怎么实现”文章已经介绍完毕,想要掌握这篇文章的知识点还需要大家自己动手实践使用过才能领会,如果想了解更多相关内容的文章,欢迎关注蜗牛博客行业资讯频道。

免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:niceseo99@gmail.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。

评论

有免费节点资源,我们会通知你!加入纸飞机订阅群

×
天气预报查看日历分享网页手机扫码留言评论电报频道链接