JavaScript Design Patterns: A closer look at effective design

Introduction
<p>Solid design patterns are the basic building blocks of maintainable software applications. If you've ever been in a technical interview, you'll love being asked these questions. In this tutorial, we'll cover some patterns you can start using today.What is a design pattern?
<p>Design patterns are reusable software solutions<p>Simply put, design patterns are reusable software solutions to specific types of problems that often occur during software development. After years of software development practice, experts have found ways to solve similar problems. These solutions have been encapsulated into design patterns. so:
- Patterns are proven solutions to software development problems
- Patterns are extensible because they are usually structured and have rules that you should follow
- Patterns can be reused to solve similar problems
Types of design patterns
<p>In software development, design patterns are usually divided into several categories. We'll cover the three most important ones in this tutorial. Here’s a brief explanation:- Creation Pattern focuses on methods of creating objects or classes. This may sound simple (and in some cases it is), but large applications require control over the object creation process. <p>
- Structure Design patterns focus on ways to manage relationships between objects in order to build applications in a scalable way. A key aspect of structural patterns is ensuring that changes to one part of the application do not affect all other parts. <p>
- Behavior Pattern focuses on communication between objects.
Notes on classes in JavaScript
<p>When reading about design patterns, you will often see references to classes and objects. This can be confusing because JavaScript doesn't really have a construct called "class"; the more correct term is "data type".Data types in JavaScript
<p>JavaScript is an object-oriented language in which objects inherit from other objects with the concept of prototypal inheritance. Data types can be created by defining so-called constructors as follows:function Person(config) { this.name = config.name; this.age = config.age; } Person.prototype.getAge = function() { return this.age; }; var tilo = new Person({name:"Tilo", age:23 }); console.log(tilo.getAge());
prototype
when defining methods on the Person
data type. Since multiple Person
objects will reference the same prototype, this allows the getAge()
method to be shared by all instances of the Person
data type, rather than for each instance redefines it. Additionally, any data type that inherits from Person
can access the getAge()
method.
Handling Privacy
<p>Another common problem in JavaScript is that there are no truly private variables. However, we can use closures to simulate privacy. Consider the following code snippet:var retinaMacbook = (function() { //Private variables var RAM, addRAM; RAM = 4; //Private method addRAM = function (additionalRAM) { RAM += additionalRAM; }; return { //Public variables and methods USB: undefined, insertUSB: function (device) { this.USB = device; }, removeUSB: function () { var device = this.USB; this.USB = undefined; return device; } }; })();
retinaMacbook
object with public and private variables and methods. This is how we use it:
retinaMacbook.insertUSB("myUSB"); console.log(retinaMacbook.USB); //logs out "myUSB" console.log(retinaMacbook.RAM) //logs out undefined
Creative Design Mode
<p> There are many different types of creative design patterns, but we'll cover two of them in this tutorial: builders and prototypes. I find that these are used often enough to cause concern.Builder Pattern
<p>The builder pattern is often used in web development, and you may have used it before without realizing it. Simply put, this pattern can be defined as follows:<p>The application builder pattern allows us to construct objects by just specifying their type and contents. We don't have to create the object explicitly.<p>For example, you may have done this countless times in jQuery:
var myDiv = $('<div id="myDiv">This is a div.</div>'); //myDiv now represents a jQuery object referencing a DOM node. var someText = $('<p/>'); //someText is a jQuery object referencing an HTMLParagraphElement var input = $('<input />');
<div/>
元素。在第二个中,我们传入了一个空的 <p>
标签。在最后一个中,我们传入了 <input />
元素。这三个的结果都是相同的:我们返回了一个引用 DOM 节点的 jQuery 对象。
<p>$
变量采用了jQuery中的Builder模式。在每个示例中,我们都返回了一个 jQuery DOM 对象,并且可以访问 jQuery 库提供的所有方法,但我们从未显式调用 document.createElement
。 JS 库在幕后处理了所有这些事情。
<p>想象一下,如果我们必须显式创建 DOM 元素并向其中插入内容,那将需要耗费多少工作!通过利用构建器模式,我们能够专注于对象的类型和内容,而不是显式创建它。
原型模式
<p>前面,我们介绍了如何通过函数在 JavaScript 中定义数据类型,以及如何向对象的prototype
添加方法。原型模式允许对象通过原型从其他对象继承。
<p>原型模式是通过克隆基于现有对象的模板来创建对象的模式。<p>这是在 JavaScript 中实现继承的一种简单而自然的方式。例如:
var Person = { numFeet: 2, numHeads: 1, numHands:2 }; //Object.create takes its first argument and applies it to the prototype of your new object. var tilo = Object.create(Person); console.log(tilo.numHeads); //outputs 1 tilo.numHeads = 2; console.log(tilo.numHeads) //outputs 2
Person
对象中的属性(和方法)应用于 tilo
对象的原型。如果我们希望它们不同,我们可以重新定义 tilo
对象的属性。
<p>在上面的例子中,我们使用了 Object.create()
。但是,Internet Explorer 8 不支持较新的方法。在这些情况下,我们可以模拟它的行为:
var vehiclePrototype = { init: function (carModel) { this.model = carModel; }, getModel: function () { console.log( "The model of this vehicle is " + this.model); } }; function vehicle (model) { function F() {}; F.prototype = vehiclePrototype; var f = new F(); f.init(model); return f; } var car = vehicle("Ford Escort"); car.getModel();
Object.create()
时指定。尽管如此,原型模式展示了对象如何从其他对象继承。
结构设计模式
<p>在弄清楚系统应该如何工作时,结构设计模式非常有用。它们使我们的应用程序能够轻松扩展并保持可维护性。我们将研究本组中的以下模式:复合模式和外观模式。复合模式
<p>复合模式是您之前可能使用过但没有意识到的另一种模式。<p>复合模式表示可以像对待组中的单个对象一样对待一组对象。<p>那么这是什么意思呢?好吧,考虑一下 jQuery 中的这个示例(大多数 JS 库都有与此等效的示例):
$('.myList').addClass('selected'); $('#myItem').addClass('selected'); //dont do this on large tables, it's just an example. $("#dataTable tbody tr").on("click", function(event){ alert($(this).text()); }); $('#myButton').on("click", function(event) { alert("Clicked."); });
selected
类添加到 .myList
选择器选取的所有项目中,但在处理单个 DOM 元素 #myItem
时,我们可以使用相同的方法。同样,我们可以使用 on()
方法在多个节点上附加事件处理程序,或者通过相同的 API 在单个节点上附加事件处理程序。
<p>通过利用复合模式,jQuery(和许多其他库)为我们提供了一个简化的 API。
<p>复合模式有时也会引起问题。在 JavaScript 等松散类型语言中,了解我们正在处理单个元素还是多个元素通常会很有帮助。由于复合模式对两者使用相同的 API,因此我们经常会误认为其中一个,并最终出现意想不到的错误。某些库(例如 YUI3)提供两种单独的获取元素的方法(Y.one()
与 Y.all()
)。
外观模式
<p>这是我们认为理所当然的另一个常见模式。事实上,这是我最喜欢的之一,因为它很简单,而且我已经看到它被到处使用来帮助解决浏览器不一致的问题。以下是外观模式的含义:<p>外观模式为用户提供了一个简单的界面,同时隐藏了其底层的复杂性。<p>外观模式几乎总能提高软件的可用性。再次以 jQuery 为例,该库中比较流行的方法之一是
ready()
方法:
$(document).ready(function() { //all your code goes here... });
ready()
方法实际上实现了一个门面。如果您查看源代码,您会发现以下内容:
ready: (function() { ... //Mozilla, Opera, and Webkit if (document.addEventListener) { document.addEventListener("DOMContentLoaded", idempotent_fn, false); ... } //IE event model else if (document.attachEvent) { // ensure firing before onload; maybe late but safe also for iframes document.attachEvent("onreadystatechange", idempotent_fn); // A fallback to window.onload, that will always work window.attachEvent("onload", idempotent_fn); ... } })
ready()
方法并不那么简单。 jQuery 规范了浏览器的不一致,以确保在适当的时间触发 ready()
。但是,作为开发人员,您会看到一个简单的界面。
<p>大多数外观模式示例都遵循这一原则。在实现时,我们通常依赖于底层的条件语句,但将其作为一个简单的界面呈现给用户。实现此模式的其他方法包括 animate()
和 css()
。你能想到为什么这些会使用外观模式吗?
行为设计模式
<p>任何面向对象的软件系统都会在对象之间进行通信。不组织这种沟通可能会导致难以发现和修复的错误。行为设计模式规定了组织对象之间通信的不同方法。在本节中,我们将研究观察者模式和中介者模式。观察者模式
<p>观察者模式是我们将要经历的两种行为模式中的第一种。它是这样说的:<p>在观察者模式中,主题可以拥有对其生命周期感兴趣的观察者列表。每当主题做了一些有趣的事情时,它都会向其观察者发送通知。如果观察者不再有兴趣听主题,则主题可以将其从列表中删除。<p>听起来很简单,对吧?我们需要三种方法来描述这种模式:
-
publish(data)
:当主题有通知要发出时调用。某些数据可以通过此方法传递。 -
subscribe(observer)
:由主题调用以将观察者添加到其观察者列表中。 -
unsubscribe(observer)
:由主题调用,从其观察者列表中删除观察者。
on()
或 attach()
方法,一个 trigger()
或 fire()
方法,以及一个 off()
或 detach()
方法。考虑以下代码片段:
//We just create an association between the jQuery events methods
//and those prescribed by the Observer Pattern but you don't have to. var o = $( {} ); $.subscribe = o.on.bind(o); $.unsubscribe = o.off.bind(o); $.publish = o.trigger.bind(o); // Usage document.on( 'tweetsReceived', function(tweets) { //perform some actions, then fire an event $.publish('tweetsShow', tweets); }); //We can subscribe to this event and then fire our own event. $.subscribe( 'tweetsShow', function() { //display the tweets somehow .. //publish an action after they are shown. $.publish('tweetsDisplayed); }); $.subscribe('tweetsDisplayed, function() { ... });
调解者模式
<p>我们要讨论的最后一个模式是中介者模式。它与观察者模式类似,但有一些显着的差异。<p>中介者模式提倡使用单个共享主题来处理与多个对象的通信。所有对象都通过中介者相互通信。<p>现实世界中一个很好的类比是空中交通塔,它负责处理机场和航班之间的通信。在软件开发领域,当系统变得过于复杂时,通常会使用中介者模式。通过放置中介,可以通过单个对象来处理通信,而不是让多个对象相互通信。从这个意义上说,中介者模式可以用来替代实现观察者模式的系统。 <p>在这个要点中,Addy Osmani 提供了中介者模式的简化实现。让我们谈谈如何使用它。想象一下,您有一个 Web 应用程序,允许用户单击专辑并播放其中的音乐。您可以像这样设置中介者:
$('#album').on('click', function(e) { e.preventDefault(); var albumId = $(this).id(); mediator.publish("playAlbum", albumId); }); var playAlbum = function(id) { … mediator.publish("albumStartedPlaying", {songList: [..], currentSong: "Without You"}); }; var logAlbumPlayed = function(id) { //Log the album in the backend }; var updateUserInterface = function(album) { //Update UI to reflect what's being played }; //Mediator subscriptions mediator.subscribe("playAlbum", playAlbum); mediator.subscribe("playAlbum", logAlbumPlayed); mediator.subscribe("albumStartedPlaying", updateUserInterface);
结论
<p>过去已经有人成功应用过它。<p>设计模式的伟大之处在于,过去已经有人成功地应用过它。有许多开源代码可以在 JavaScript 中实现各种模式。作为开发人员,我们需要了解现有的模式以及何时应用它们。我希望本教程可以帮助您在回答这些问题上更进一步。
补充阅读
<p>本文的大部分内容可以在 Addy Osmani 所著的优秀的《学习 JavaScript 设计模式》一书中找到。这是一本根据知识共享许可免费发布的在线图书。本书广泛涵盖了许多不同模式的理论和实现,包括普通 JavaScript 和各种 JS 库。我鼓励您在开始下一个项目时将其作为参考。The above is the detailed content of JavaScript Design Patterns: A closer look at effective design. For more information, please follow other related articles on the PHP Chinese website!

Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

Video Face Swap
Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Article

Hot Tools

Notepad++7.3.1
Easy-to-use and free code editor

SublimeText3 Chinese version
Chinese version, very easy to use

Zend Studio 13.0.1
Powerful PHP integrated development environment

Dreamweaver CS6
Visual web development tools

SublimeText3 Mac version
God-level code editing software (SublimeText3)

Hot Topics

Blogs are the ideal platform for people to express their opinions, opinions and opinions online. Many newbies are eager to build their own website but are hesitant to worry about technical barriers or cost issues. However, as the platform continues to evolve to meet the capabilities and needs of beginners, it is now starting to become easier than ever. This article will guide you step by step how to build a WordPress blog, from theme selection to using plugins to improve security and performance, helping you create your own website easily. Choose a blog topic and direction Before purchasing a domain name or registering a host, it is best to identify the topics you plan to cover. Personal websites can revolve around travel, cooking, product reviews, music or any hobby that sparks your interests. Focusing on areas you are truly interested in can encourage continuous writing

Recently, we showed you how to create a personalized experience for users by allowing users to save their favorite posts in a personalized library. You can take personalized results to another level by using their names in some places (i.e., welcome screens). Fortunately, WordPress makes it very easy to get information about logged in users. In this article, we will show you how to retrieve information related to the currently logged in user. We will use the get_currentuserinfo(); function. This can be used anywhere in the theme (header, footer, sidebar, page template, etc.). In order for it to work, the user must be logged in. So we need to use

Do you want to know how to display child categories on the parent category archive page? When you customize a classification archive page, you may need to do this to make it more useful to your visitors. In this article, we will show you how to easily display child categories on the parent category archive page. Why do subcategories appear on parent category archive page? By displaying all child categories on the parent category archive page, you can make them less generic and more useful to visitors. For example, if you run a WordPress blog about books and have a taxonomy called "Theme", you can add sub-taxonomy such as "novel", "non-fiction" so that your readers can

WordPress is easy for beginners to get started. 1. After logging into the background, the user interface is intuitive and the simple dashboard provides all the necessary function links. 2. Basic operations include creating and editing content. The WYSIWYG editor simplifies content creation. 3. Beginners can expand website functions through plug-ins and themes, and the learning curve exists but can be mastered through practice.

There are four ways to adjust the WordPress article list: use theme options, use plugins (such as Post Types Order, WP Post List, Boxy Stuff), use code (add settings in the functions.php file), or modify the WordPress database directly.

In the past, we have shared how to use the PostExpirator plugin to expire posts in WordPress. Well, when creating the activity list website, we found this plugin to be very useful. We can easily delete expired activity lists. Secondly, thanks to this plugin, it is also very easy to sort posts by post expiration date. In this article, we will show you how to sort posts by post expiration date in WordPress. Updated code to reflect changes in the plugin to change the custom field name. Thanks Tajim for letting us know in the comments. In our specific project, we use events as custom post types. Now

One of our users asked other websites how to display the number of queries and page loading time in the footer. You often see this in the footer of your website, and it may display something like: "64 queries in 1.248 seconds". In this article, we will show you how to display the number of queries and page loading time in WordPress. Just paste the following code anywhere you like in the theme file (e.g. footer.php). queriesin

Can learn WordPress within three days. 1. Master basic knowledge, such as themes, plug-ins, etc. 2. Understand the core functions, including installation and working principles. 3. Learn basic and advanced usage through examples. 4. Understand debugging techniques and performance optimization suggestions.
