Upload
derek-brown
View
544
Download
1
Embed Size (px)
DESCRIPTION
Great design patterns are reusable, modular expressions of what’s going on in your code. They allow you to communicate to other developers simply by the way you code, in addition to being easily maintainable themselves. Put simply, patterns are the available tools in the developer’s toolbox. In this presentation, I review a few common patterns, their advantages/disadvantages, and how they can be implemented. The source for this presentation can be found here: https://github.com/derekbrown/designpatterns
Citation preview
JavaScript PatternsAdding Tools to Your Toolbox
/ Derek Brown @derekbrown
QuestionCan you drive a nail into a board using a Phillips-head
screwdriver?
AnswerYep. But it'll suck. Get a hammer, moron.
Why Patterns?Great design patterns are reusable, modular expressions of
what's going on in your code. They allow you to
communicate to other developers simply by the way you
code, in addition to being easily maintainable themselves.
Put simply, patterns are the available tools in the
developer's toolbox.
The Patterns We'll CoverThere are hundreds of design patterns that can be
leveraged for use here in your code base. Ain't nobody got
time for that, so we'll cover only a few that are pretty
different from one another, but are prevalent in
applications, to get a glance at what's out there.
For each pattern, we'll look at the following:
Definition
Code Sample
Advantages & Disadvantages
Common Usage
Module / Revealing ModuleYou are already familiar with this pattern. Trust me. It's one
of the most common patterns on the web.
SingletonThere can be only one....instance of this object.
FacadeA facade is exactly what it sounds like: makeup on a bulldog.
You're covering over complex, ugly things with a simplified
interface for future, more scalable development.
CommandThis pattern is useful for action-oriented objects.
FactoryThe factory pattern lets you encapsulate multiple types of
objects within a categorical constructor.
ObserverThis is a pattern that we've talked about previously, within
the context of Ember. But how can you implement a
publish/subscribe model yourself? And when should you?
DelegateDelegates are a pattern that allow for event-like
communication between components.
Module / Revealing ModuleThis is one of the most fundamental design patterns in the
JavaScript universe. It's primary use is to include both
private and public variables within a single class-like object
while at the same time protecting the private
methods/properties from the application.
Modules accomplish this encapsulation by using closures to
protect the private pieces while allowing the developer to
determine which pieces of the object should be publicly
exposed to the rest of the application.
Module / Revealing Module
var myModule = (function () {
var myProperty = 'Value';
return { getProperty: function () { return myProperty; },
setProperty: function (newValue) { myProperty = newValue; } }; })();
myModule.getProperty(); // Returns 'Value' myModule.setProperty('New Value'); myModule.getProperty(); // Returns 'New Value'
Module / Revealing ModuleMy return object is going to get a bit messy....
Module / Revealing Module var myModule = (function () {
var myProperty = 'Value';
function getProperty () { return myProperty; }
function setProperty (newValue) { myProperty = newValue; }
return { get: getProperty, set: setProperty };
})();
myModule.get(); // Returns 'Value' myModule.set('New Value'); myModule.get(); // Returns 'New Value'
Advantages: ModuleClean, readable, & consistent syntax.
Less clutter in the global namespace.
Allows developers to control scope of properties & methods.
Localization of functions & variables
Disadvantages: ModuleUnit testing can be difficult if the methods aren't exposed.
Private methods are unaccessible.
Can't easily extend private methods.
Common UsageEverything. <\sarcasm>
But really.
SingletonThe singleton pattern is extremely useful if you only one
instance of the object to ever exist. Basically, what occurs
within the Singleton pattern is that you write your object,
and then as a part of that object, you have an additional
method. This function simply checks if an instance of the
object already exists. If it does, use that instance. If not, then
create a new one and store the reference.
Singleton var mySingleton = (function () {
var instance, myProperty = 'Value';
function getProperty () { return myProperty; }
function setProperty (newValue) { myProperty = newValue; }
function initialize () { return { get: getProperty, set: setProperty }; }
return { getInstance: function () {
if ( !instance ) { instance = initialize();
Advantages: SingletonReduced memory usage
Single point of access
Delayed initialization prevents instantiation until required
Disadvantages: SingletonOnce an instance exists, it's difficult to "reset".
Harder to unit test.
Common UsageApplication Instances.
FacadeThe facade pattern is often paired with other patterns to
add an extra layer of security while at the same time
providing a simpler interface to the underlying functionality.
Facade var myFacade = (function () {
var myProperty = 'Value';
function getProperty () { return myProperty; };
function setProperty (newValue) { myProperty = newValue; }
return { get: function () { return getProperty(); }, set: function (newValue) { setProperty(newValue); } };
})();
Advantages: FacadeEnhances security, as internal functions aren't exposed.
Easy to implement
Works well with other design patterns.
Easy to patch internals
Provides a simple public interface
Disadvantages: FacadeIs the cost of implementation really worth the extra layer of
abstraction?
Common UsageOne of the most prevalent uses of the Facade pattern ever:
jQuery
CommandThe command pattern completely separates the
implementation and execution of methods. Usually, in order
to execute a method, you directly invoke the method itself.
The command pattern takes the name of the method to
execute as an argument into an "execute" or "run" method
on the command object, applying the rest of the arguments
list to the function being invoked.
In most programming, objects represent nouns. In the
command pattern, objects are verbs.
Command var myCommand = {
requestData: function (id, attribute) { return 'Data attribute ' + attribute + ' has been requested for object ' },
clearData: function (id, attribute) { return 'The data attribute ' + attribute + ' has been reset for object ' }
}
myCommand.run = function (command) { return myCommand[command.request](command.id, command.attribute) };
/* Alternatively, the run function could look like this, which would pass extra myCommand.run = function (command) { return myCommand[command].apply( myCommand, [].slice.call(arguments, 1)); };
or for argumentless commands, you can go even simpler:
myCommand.run = function (command) {
Advantages: CommandDecouples implementation from execution, which allows for
extensibility while minimizing code changes.
Stacking command objects allows you to cache them, store them in a
history, or otherwise manipulate them. Undo, anyone?
Disadvantages: CommandCounter-intuitive to most OOP practices.
Very limited use to 'verb-centric' applications.
Common UsageCommand Line Interfaces for Node.js
FactoryThe factory pattern is as a interface that can be used to
create objects, usually which belong to a set or category.
The factory takes in the attributes of the object to be
created, and then returns a new instance of our object.
Factoryfunction Manager ( config ) { this.name = config.name || 'Michael Scott'; this.role = config.role || 0; this.user = config.user || 'MichaelScott123';}
function Contributor ( config ) { this.name = config.name || 'Bob Smith'; this.role = config.role || 1; this.user = config.user || 'BobSmith123'; this.mngr = config.mngr || 'MichaelScott123';}
function Contractor ( config ) { this.name = config.name || 'John Doe'; this.role = config.role || 2; this.user = config.user || 'JohnDoe123'; this.mngr = config.mngr || 'MichaelScott123'; this.term = config.term || '6 months';}
function WorkerFactory() {}
WorkerFactory.prototype.employeeClass = Contributor;WorkerFactory.prototype.hireSomeone = function ( config ){
Advantages: FactoryAllows the sharing of properties across multiple objects.
Extremely useful when object or component setup is complex.
Also useful when you need to generate different instances based on
context.
Disadvantages: FactoryFairly complex for smaller applications.
Garbage collection can have high overhead.
Can introduce problems with unit testing.
Common UsageAddress Book (contacts), To-Do App (tasks)
ObserverIn the observer pattern, a type of publish-subscribe pattern,
there is an object (often called the subject or observable)
that notifies other objects (observers) of any changes that
occur to the state of the subject. The observers are often
maintained in a list on the observable, to be iterated upon
when a change occurs.
Observer var observer = { addSubscriber: function (callback) { this.subscribers[this.subscribers.length] = callback; },
removeSubscriber: function (callback) { for (var i = 0; i < this.subscribers.length; i++) { if (this.subscribers[i] === callback) { delete(this.subscribers[i]); } } },
publish: function (what) { for (var i = 0; i < this.subscribers.length; i++) { if (typeof this.subscribers[i] === 'function') { this.subscribers[i](what); } } },
makePublisher: function (o) { // turns an object into a publisher for (var i in this) { o[i] = this[i]; o.subscribers = [];
Source: For another example using Ember's implementation, check out Chad Hietala's ConnectionViewer repository.
Advantages: ObserverFaciliates application-level thinking.
Removes direct relationships that are often unnecessary.
Can relate objects without tightly coupling them.
Disadvantages: ObserverThere is no way to know if the other end of the telephone is still
listening.
Subscribers aren't aware of one another.
Common UsageYUI Custom Events. Ember Observables.
DelegateIn the delegate pattern, an object (the delegator) offloads a
task to an associated helper object (the delegate), rather
than performing the task itself. Often times, this is within an
MVC framework or architecture, involving a Controller as
the delegator.
Delegatevar ViewClass = function () { return { init : function (el) { var $el = $(el);
// REQUIRED: delegate should have a viewWasClicked method implemented $el.on('click', this.delegate.viewWasClicked); }, delegate : null };};
var ControllerClass = function () { return { viewWasClicked : function (e) { console.log('I was called!'); } }};
var controller = new ControllerClass();var view = new ViewClass();
view.delegate = controller;view.init(document.getElementById('myHeader'));
Source: David Drew's fantastic article on implementing Objective-C Delegates in JavaScript
Advantages: DelegateDelegation allows for loose coupling without global eventing.
Easy to maintain structure within an application.
Disadvantages: DelegateNo well-structured way to enforce delegation attachment.
Assignment of delegate takes place prior to initialization.
Common UsageMost MVC frameworks at least involve delegation in their
design in some regard, due to the interaction between
models, views, and controllers.
Helpful Resources & ReadingLearning JavaScript Design Patterns by Addy Osmani
JavaScript Patterns on GitHub
Carl Danley: JavaScript Design Patterns
JavaScript Design Patterns on Adobe DevNet
Pro JavaScript Design Patterns
Zakas on the Factory Pattern
JavaScript Design Patterns
Fin.