JAVASCRIPT PATTERNS EBOOK

adminComment(0)

An open-source book on JavaScript Design Patterns. for both free online and as a physical (or eBook) download for readers wishing to support the project. Nutshell Handbook, the Nutshell Handbook logo, and the O'Reilly logo are registered trademarks of. O'Reilly Media, Inc. JavaScript Patterns, the image of a . Editorial Reviews. Book Description. Build Better Applications with Coding and Design Patterns venarefeane.cf: JavaScript Patterns: Build Better Applications with Coding and Design Patterns eBook: Stoyan Stefanov: site Store.


Javascript Patterns Ebook

Author:RETA CELLUPICA
Language:English, Portuguese, Dutch
Country:Palau
Genre:Politics & Laws
Pages:217
Published (Last):04.08.2016
ISBN:237-6-28008-205-9
ePub File Size:16.68 MB
PDF File Size:12.61 MB
Distribution:Free* [*Register to download]
Downloads:45769
Uploaded by: CATHERIN

Read "JavaScript Patterns Build Better Applications with Coding and Design Patterns" by Stoyan Stefanov available from Rakuten Kobo. Sign up today and get. JavaScript Patterns: Build Better Applications with Coding and Design Patterns ( English Edition) 1st Edition, eBook site. por Stoyan Stefanov (Autor). What's the best approach for developing an application with JavaScript? This book helps you answer that question with numerous JavaScript coding patterns.

Here, getInstance becomes a little like a Factory method and we don't need to update each point in our code accessing it. FooSingleton above would be a subclass of BasicSingleton and implement the same interface. It is important to note the difference between a static instance of a class object and a Singleton: If we have a static object that can be initialized directly, we need to ensure the code is always executed in the same order e.

Both Singletons and static objects are useful but they shouldn't be overused - the same way in which we shouldn't overuse other patterns. In practice, the Singleton pattern is useful when exactly one object is needed to coordinate others across a system. Here is one example with the pattern being used in this context:. Whilst the Singleton has valid uses, often when we find ourselves needing it in JavaScript it's a sign that we may need to re-evaluate our design.

They're often an indication that modules in a system are either tightly coupled or that logic is overly spread across multiple parts of a codebase. Singletons can be more difficult to test due to issues ranging from hidden dependencies, the difficulty in creating multiple instances, difficulty in stubbing dependencies and so on. Miller Medeiros has previously recommended this excellent article on the Singleton and its various issues for further reading as well as the comments to this article, discussing how Singletons can increase tight coupling.

I'm happy to second these recommendations as both pieces raise many important points about this pattern that are also worth noting. The Observer is a design pattern where an object known as a subject maintains a list of objects depending on it observers , automatically notifying them of any changes to state. When a subject needs to notify observers about something interesting happening, it broadcasts a notification to the observers which can include specific data related to the topic of the notification.

When we no longer wish for a particular observer to be notified of changes by the subject they are registered with, the subject can remove them from the list of observers. It's often useful to refer back to published definitions of design patterns that are language agnostic to get a broader sense of their usage and advantages over time.

Elements of Reusable Object-Oriented Software , is:. When something changes in our subject that the observer may be interested in, a notify message is sent which calls the update method in each observer. When the observer is no longer interested in the subject's state, they can simply detach themselves.

We can now expand on what we've learned to implement the Observer pattern with the following components:. Next, let's model the Subject and the ability to add, remove or notify observers on the observer list. We then define a skeleton for creating new Observers.

The update functionality here will be overwritten later with custom behaviour. We then define ConcreteSubject and ConcreteObserver handlers for both adding new observers to the page and implementing the updating interface. See below for inline comments on what these components do in the context of our example. In this example, we looked at how to implement and utilize the Observer pattern, covering the concepts of a Subject, Observer, ConcreteSubject and ConcreteObserver.

Whilst very similar, there are differences between these patterns worth noting. The Observer pattern requires that the observer or object wishing to receive topic notifications must subscribe this interest to the object firing the event the subject. This event system allows code to define application specific events which can pass custom arguments containing values needed by the subscriber.

The idea here is to avoid dependencies between the subscriber and publisher. This differs from the Observer pattern as it allows any subscriber implementing an appropriate event handler to register for and receive topic notifications broadcast by the publisher.

The general idea here is the promotion of loose coupling. Rather than single objects calling on the methods of other objects directly, they instead subscribe to a specific task or activity of another object and are notified when it occurs.

They also help us identify what layers containing direct relationships which could instead be replaced with sets of subjects and observers. This effectively could be used to break down an application into smaller, more loosely coupled blocks to improve code management and potentials for re-use. Further motivation behind using the Observer pattern is where we need to maintain consistency between related objects without making classes tightly coupled.

For example, when an object needs to be able to notify other objects without making assumptions regarding those objects. Dynamic relationships can exist between observers and subjects when using either pattern. This provides a great deal of flexibility which may not be as easy to implement when disparate parts of our application are tightly coupled. Whilst it may not always be the best solution to every problem, these patterns remain one of the best tools for designing decoupled systems and should be considered an important tool in any JavaScript developer's utility belt.

Consequently, some of the issues with these patterns actually stem from their main benefits. For example, publishers may make an assumption that one or more subscribers are listening to them. Say that we're using such an assumption to log or output errors regarding some application process. If the subscriber performing the logging crashes or for some reason fails to function , the publisher won't have a way of seeing this due to the decoupled nature of the system.

Another draw-back of the pattern is that subscribers are quite ignorant to the existence of each other and are blind to the cost of switching publishers.

Due to the dynamic relationship between subscribers and publishers, the update dependency can be difficult to track. Below we can see some examples of this:. Links to just a few of these can be found below.

This demonstrates the core concepts of subscribe, publish as well as the concept of unsubscribing. I've opted to base our examples on this code as it sticks closely to both the method signatures and approach of implementation I would expect to see in a JavaScript version of the classic Observer pattern.

Next, let's imagine we have a web application responsible for displaying real-time stock information.

The application might have a grid for displaying the stock stats and a counter for displaying the last point of update.

When the data model changes, the application will need to update the grid and counter. When our subscribers receive notification that the model itself has changed, they can update themselves accordingly. In our implementation, our subscriber will listen to the topic "newDataAvailable" to find out if new stock information is available.

If a new notification is published to this topic, it will trigger gridUpdate to add a new row to our grid containing this information. It will also update a last updated counter to log the last time data was added.

Notice how submitting a rating only has the effect of publishing the fact that new user and rating data is available. It's left up to the subscribers to those topics to then delegate what happens with that data.

In our case we're pushing that new data into existing arrays and then rendering them using the Underscore library's. Quite often in Ajax-heavy applications, once we've received a response to a request we want to achieve more than just one unique action. One could simply add all of their post-request logic into a success callback, but there are drawbacks to this approach.

What this means is that although keeping our post-request logic hardcoded in a callback might be fine if we're just trying to grab a result set once, it's not as appropriate when we want to make further Ajax-calls to the same data source and different end-behavior without rewriting parts of the code multiple times.

Using Observers, we can also easily separate application-wide notifications regarding different events down to whatever level of granularity we're comfortable with - something which can be less elegantly done using other patterns. Notice how in our sample below, one topic notification is made when a user indicates they want to make a search query and another is made when the request returns and actual data is available for consumption. It's left up to the subscribers to then decide how to use knowledge of these events or the data returned.

The benefits of this are that, if we wanted, we could have 10 different subscribers utilizing the data returned in different ways but as far as the Ajax-layer is concerned, it doesn't care.

Its sole duty is to request and return data then pass it on to whoever wants to use it. This separation of concerns can make the overall design of our code a little cleaner. The Observer pattern is useful for decoupling a number of different scenarios in application design and if you haven't been using it, I recommend picking up one of the pre-written implementations mentioned today and just giving it a try out.

It's one of the easier design patterns to get started with but also one of the most powerful. In the section on the Observer pattern, we were introduced to a way of channeling multiple event sources through a single object.

It's common for developers to think of Mediators when faced with this problem, so let's explore how they differ. The dictionary refers to a mediator as a neutral party that assists in negotiations and conflict resolution. In our world, a mediator is a behavioral design pattern that allows us to expose a unified interface through which the different parts of a system may communicate. If it appears a system has too many direct relationships between components, it may be time to have a central point of control that components communicate through instead.

The Mediator promotes loose coupling by ensuring that instead of components referring to each other explicitly, their interaction is handled through this central point.

This can help us decouple systems and improve the potential for component reusability. A real-world analogy could be a typical airport traffic control system. A tower Mediator handles what planes can take off and land because all communications notifications being listened out for or broadcast are done from the planes to the control tower, rather than from plane-to-plane. A centralized controller is key to the success of this system and that's really the role a Mediator plays in software design.

Another analogy would be DOM event bubbling and event delegation. If all subscriptions in a system are made against the document rather than individual nodes, the document effectively serves as a Mediator. Instead of binding to the events of the individual nodes, a higher level object is given the responsibility of notifying subscribers about interaction events. When it comes to the Mediator and Event Aggregator patterns, there are some times where it may look like the patterns are interchangeable due to implementation similarities.

However, the semantics and intent of these patterns are very different. And even if the implementations both use some of the same core constructs, I believe there is a distinct difference between them.

I also believe they should not be interchanged or confused in communication because of the differences. A Mediator is an object that coordinates interactions logic and behavior between multiple objects. It makes decisions on when to call which objects, based on the actions or inaction of other objects and input. Yes, of course this is just an object literal in JavaScript.

This example shows a very basic implementation of a mediator object with some utility methods that can trigger and subscribe to events. It is an object that handles the workflow between many other objects, aggregating the responsibility of that workflow knowledge into a single object.

The result is workflow that is easier to understand and maintain. The similarities boil down to two primary items: These differences are superficial at best, though. When we dig into the intent of the pattern and see that the implementations can be dramatically different, the nature of the patterns become more apparent.

Both the event aggregator and mediator use events, in the above examples. The mediator only uses events because it makes life easy when dealing with modern JavaScript webapp frameworks. There is nothing that says a mediator must be built with events. You can build a mediator with callback methods, by handing the mediator reference to the child object, or by any of a number of other means.

The difference, then, is why these two patterns are both using events. The event aggregator, as a pattern, is designed to deal with events. Both the event aggregator and mediator, by design, use a third-party object to facilitate things.

The event aggregator itself is a third-party to the event publisher and the event subscriber. It acts as a central hub for events to pass through. The mediator is also a third party to other objects, though. So where is the difference? The answer largely comes down to where the application logic and workflow is coded.

In the case of an event aggregator, the third party object is there only to facilitate the pass-through of events from an unknown number of sources to an unknown number of handlers. All workflow and business logic that needs to be kicked off is put directly into the object that triggers the events and the objects that handle the events. In the case of the mediator, though, the business logic and workflow is aggregated into the mediator itself.

The mediator decides when an object should have its methods called and attributes updated based on factors that the mediator knows about. It encapsulates the workflow and process, coordinating multiple objects to produce the desired system behaviour. The individual objects involved in this workflow each know how to perform their own task.

It just fires the event and moves on. A mediator pays attention to a known set of input or activities so that it can facilitate and coordinate additional behavior with a known set of actors objects. Understanding the similarities and differences between an event aggregator and mediator is important for semantic reasons.

The basic semantics and intent of the patterns does inform the question of when, but actual experience in using the patterns will help you understand the more subtle points and nuanced decisions that have to be made. In general, an event aggregator is used when you either have too many objects to listen to directly, or you have objects that are entirely unrelated. When two objects have a direct relationship already — say, a parent view and child view — there may be benefit in using an event aggregator.

Have the child view trigger an event and the parent view can handle the event. A Collection often uses model events to modify the state of itself or other models. This could quickly deteriorate performance of the application and user experience. Indirect relationships are also a great time to use event aggregators. In modern applications, it is very common to have multiple view objects that need to communicate, but have no direct relationship.

For example, a menu system might have a view that handles the menu item clicks. Having the content and menu coupled together would make the code very difficult to maintain, in the long run. A mediator is best applied when two or more objects have an indirect working relationship, and business logic or workflow needs to dictate the interactions and coordination of these objects.

There are multiple views that facilitate the entire workflow of the wizard.

Learning Javascript Design Patterns

Rather than tightly coupling the view together by having them reference each other directly, we can decouple them and more explicitly model the workflow between them by introducing a mediator. The mediator extracts the workflow from the implementation details and creates a more natural abstraction at a higher level, showing us at a much faster glance what that workflow is. We no longer have to dig into the details of each view in the workflow, to see what the workflow actually is.

The crux of the difference between an event aggregator and a mediator, and why these pattern names should not be interchanged with each other, is illustrated best by showing how they can be used together. The menu example for an event aggregator is the perfect place to introduce a mediator as well.

Clicking a menu item may trigger a series of changes throughout an application. Some of these changes will be independent of others, and using an event aggregator for this makes sense. Some of these changes may be internally related to each other, though, and may use a mediator to enact those changes. A mediator, then, could be set up to listen to the event aggregator. It could run its logic and process to facilitate and coordinate many objects that are related to each other, but unrelated to the original event source.

An event aggregator and a mediator have been combined to create a much more meaningful experience in both the code and the application itself.

The JavaScript language

We now have a clean separation between the menu and the workflow through an event aggregator and we are still keeping the workflow itself clean and maintainable through the use of a mediator.

Adding new publishers and subscribers is relatively easy due to the level of decoupling present. Perhaps the biggest downside of using the pattern is that it can introduce a single point of failure.

Placing a Mediator between modules can also cause a performance hit as they are always communicating indirectly. Because of the nature of loose coupling, it's difficult to establish how a system might react by only looking at the broadcasts. That said, it's useful to remind ourselves that decoupled systems have a number of other benefits - if our modules communicated with each other directly, changes to modules e. This problem is less of a concern with decoupled systems.

At the end of the day, tight coupling causes all kinds of headaches and this is just another alternative solution, but one which can work very well if implemented correctly. We will be covering the Facade pattern shortly, but for reference purposes some developers may also wonder whether there are similarities between the Mediator and Facade patterns.

They do both abstract the functionality of existing modules, but there are some subtle differences. The Mediator centralizes communication between modules where it's explicitly referenced by these modules. In a sense this is multidirectional. The Facade however just defines a simpler interface to a module or system but doesn't add any additional functionality. Other modules in the system aren't directly aware of the concept of a facade and could be considered unidirectional.

The GoF refer to the prototype pattern as one which creates objects based on a template of an existing object through cloning. We can think of the prototype pattern as being based on prototypal inheritance where we create objects which act as prototypes for other objects.

The prototype object itself is effectively used as a blueprint for each object the constructor creates. If the prototype of the constructor function used contains a property called name for example as per the code sample lower down , then each object created by that same constructor will also have this same property.

Reviewing the definitions for this pattern in existing non-JavaScript literature, we may find references to classes once again. The reality is that prototypal inheritance avoids using classes altogether. There isn't a "definition" object nor a core object in theory.

We're simply creating copies of existing functional objects.

One of the benefits of using the prototype pattern is that we're working with the prototypal strengths JavaScript has to offer natively rather than attempting to imitate features of other languages. With other design patterns, this isn't always the case.

See a Problem?

Not only is the pattern an easy way to implement inheritance, but it can also come with a performance boost as well: For those interested, real prototypal inheritance, as defined in the ECMAScript 5 standard, requires the use of Object. To remind ourselves, Object. We saw earlier that Object. For example:. Here the properties can be initialized on the second argument of Object. It is worth noting that prototypal relationships can cause trouble when enumerating properties of objects and as Crockford recommends wrapping the contents of the loop in a hasOwnProperty check.

If we wish to implement the prototype pattern without directly using Object. This alternative does not allow the user to define read-only properties in the same manner as the vehiclePrototype may be altered if not careful.

One could reference this method from the vehicle function. Note, however that vehicle here is emulating a constructor, since the prototype pattern does not include any notion of initialization beyond linking an object to a prototype. The Command pattern aims to encapsulate method invocation, requests or operations into a single object and gives us the ability to both parameterize and pass method calls around that can be executed at our discretion.

In addition, it enables us to decouple objects invoking the action from the objects which implement them, giving us a greater degree of overall flexibility in swapping out concrete classes objects. Concrete classes are best explained in terms of class-based programming languages and are related to the idea of abstract classes.

An abstract class defines an interface, but doesn't necessarily provide implementations for all of its member functions. It acts as a base class from which others are derived. A derived class which implements the missing functionality is called a concrete class. The general idea behind the Command pattern is that it provides us a means to separate the responsibilities of issuing commands from anything executing commands, delegating this responsibility to different objects instead.

Implementation wise, simple command objects bind together both an action and the object wishing to invoke the action. They consistently include an execution operation such as run or execute. All Command objects with the same interface can easily be swapped as needed and this is considered one of the larger benefits of the pattern.

Taking a look at the above code, it would be trivial to invoke our carManager methods by directly accessing the object. We would all be forgiven for thinking there is nothing wrong with this - technically, it's completely valid JavaScript. There are however scenarios where this may be disadvantageous. For example, imagine if the core API behind the carManager changed.

This would require all objects directly accessing these methods within our application to also be modified. This could be viewed as a layer of coupling which effectively goes against the OOP methodology of loosely coupling objects as much as possible.

Instead, we could solve this problem by abstracting the API away further. Let's now expand on our carManager so that our application of the Command pattern results in the following: As per this structure we should now add a definition for the carManager. When we put up a facade, we present an outward appearance to the world which may conceal a very different reality.

This was the inspiration for the name behind the next pattern we're going to review - the Facade pattern. This pattern provides a convenient higher-level interface to a larger body of code, hiding its true underlying complexity. Think of it as simplifying the API being presented to other developers, something which almost always improves usability.

Facades are a structural pattern which can often be seen in JavaScript libraries like jQuery where, although an implementation may support methods with a wide range of behaviors, only a "facade" or limited abstraction of these methods is presented to the public for use. This allows us to interact with the Facade directly rather than the subsystem behind the scenes.

The jQuery core methods should be considered intermediate abstractions. To build on what we've learned, the Facade pattern both simplifies the interface of a class and it also decouples the class from the code that utilizes it.

This gives us the ability to indirectly interact with subsystems in a way that can sometimes be less prone to error than accessing the subsystem directly. A Facade's advantages include ease of use and often a small size-footprint in implementing the pattern. This is an unoptimized code example, but here we're utilizing a Facade to simplify an interface for listening to events cross-browser.

Internally, this is actually being powered by a method called bindReady , which is doing this:. Facades don't just have to be used on their own, however. They can also be integrated with other patterns such as the Module pattern.

As we can see below, our instance of the module patterns contains a number of methods which have been privately defined. A Facade is then used to supply a much simpler API to accessing these methods:. In this example, calling module. Facades generally have few disadvantages, but one concern worth noting is performance. Namely, one must determine whether there is an implicit cost to the abstraction a Facade offers to our implementation and if so, whether this cost is justifiable.

Did you know however that getElementById on its own is significantly faster by a high order of magnitude? Take a look at this jsPerf test to see results on a per-browser level: Now of course, we have to keep in mind that jQuery and Sizzle - its selector engine are doing a lot more behind the scenes to optimize our query and that a jQuery object, not just a DOM node is returned. The challenge with this particular Facade is that in order to provide an elegant selector function capable of accepting and parsing multiple types of queries, there is an implicit cost of abstraction.

The user isn't required to access jQuery. That said, the trade-off in performance has been tested in practice over the years and given the success of jQuery, a simple Facade actually worked out very well for the team. When using the pattern, try to be aware of any performance costs involved and make a call on whether they are worth the level of abstraction offered.

The Factory pattern is another creational pattern concerned with the notion of creating objects. Where it differs from the other patterns in its category is that it doesn't explicitly require us to use a constructor. Instead, a Factory can provide a generic interface for creating objects, where we can specify the type of factory object we wish to be created. Imagine that we have a UI factory where we are asked to create a type of UI component. Rather than creating this component directly using the new operator or via another creational constructor, we ask a Factory object for a new component instead.

We inform the Factory what type of object is required e. This is particularly useful if the object creation process is relatively complex, e.

Examples of this pattern can be found in UI libraries such as ExtJS where the methods for creating objects or components may be further subclassed. The following is an example that builds upon our previous snippets using the Constructor pattern logic to define cars.

It demonstrates how a Vehicle Factory may be implemented using the Factory pattern:. Car object of color "yellow", doors: Modify a VehicleFactory instance to use the Truck class. Approach 2: Subclass VehicleFactory to create a factory class that builds Trucks.

The Factory pattern can be especially useful when applied to the following situations: When our object or component setup involves a high level of complexity When we need to easily generate different instances of objects depending on the environment we are in When we're working with many small objects or components that share the same properties When composing objects with instances of other objects that need only satisfy an API contract aka, duck typing to work.

This is useful for decoupling. When applied to the wrong type of problem, this pattern can introduce an unnecessarily great deal of complexity to an application. Unless providing an interface for object creation is a design goal for the library or framework we are writing, I would suggest sticking to explicit constructors to avoid the unnecessary overhead.

Due to the fact that the process of object creation is effectively abstracted behind an interface, this can also introduce problems with unit testing depending on just how complex this process might be.

It is also useful to be aware of the Abstract Factory pattern, which aims to encapsulate a group of individual factories with a common goal. It separates the details of implementation of a set of objects from their general usage. An Abstract Factory should be used where a system must be independent from the way the objects it creates are generated or it needs to work with multiple types of objects. An example which is both simple and easier to understand is a vehicle factory, which defines ways to get or register vehicles types.

The abstract factory can be named abstractVehicleFactory. The Abstract factory will allow the definition of types of vehicle like "car" or "truck" and concrete factories will implement only classes that fulfill the vehicle contract e. For developers unfamiliar with sub-classing, we will go through a brief beginners primer on them before diving into Mixins and Decorators further. Sub-classing is a term that refers to inheriting properties for a new object from a base or superclass object.

In traditional object-oriented programming, a class B is able to extend another class A. Here we consider A a superclass and B a subclass of A. As such, all instances of B inherit the methods from A. B is however still able to define its own methods, including those that override methods originally defined by A. Should B need to invoke a method in A that has been overridden, we refer to this as method chaining. Should B need to invoke the constructor A the superclass , we call this constructor chaining.

In order to demonstrate sub-classing, we first need a base object that can have new instances of itself created. Next, we'll want to specify a new class object that's a subclass of the existing Person object. Let us imagine we want to add distinct properties to distinguish a Person from a Superhero whilst inheriting the properties of the Person "superclass". As superheroes share many common traits with normal people e.

The Superhero constructor creates an object which descends from Person. Objects of this type have attributes of the objects that are above it in the chain and if we had set default values in the Person object, Superhero is capable of overriding any inherited values with values specific to it's object. In JavaScript, we can look at inheriting from Mixins as a means of collecting functionality through extension.

Each new object we define has a prototype from which it can inherit further properties. Prototypes can inherit from other object prototypes but, even more importantly, can define properties for any number of object instances.

We can leverage this fact to promote function re-use. Mixins allow objects to borrow or inherit functionality from them with a minimal amount of complexity. As the pattern works well with JavaScripts object prototypes, it gives us a fairly flexible way to share functionality from not just one Mixin, but effectively many through multiple inheritance.

They can be viewed as objects with attributes and methods that can be easily shared across a number of other object prototypes. Imagine that we define a Mixin containing utility functions in a standard object literal as follows:.

We can then easily extend the prototype of existing constructor functions to include this behavior using a helper such as the Underscore. As we can see, this allows us to easily "mix" in common behaviour into object constructors fairly trivially. In the next example, we have two constructors: What we're going to do is augment another way of saying extend the Car so that it can inherit specific methods defined in the Mixin, namely driveForward and driveBackward.

This time we won't be using Underscore. Instead, this example will demonstrate how to augment a constructor to include functionality without the need to duplicate this process for every constructor function we may have.

Mixins assist in decreasing functional repetition and increasing function re-use in a system. Where an application is likely to require shared behaviour across object instances, we can easily avoid any duplication by maintaining this shared functionality in a Mixin and thus focusing on implementing only the functionality in our system which is truly distinct.

That said, the downsides to Mixins are a little more debatable. Some developers feel that injecting functionality into an object prototype is a bad idea as it leads to both prototype pollution and a level of uncertainty regarding the origin of our functions.

In large systems this may well be the case. I would argue that strong documentation can assist in minimizing the amount of confusion regarding the source of mixed in functions, but as with every pattern, if care is taken during implementation we should be okay. Decorators are a structural design pattern that aim to promote code re-use. Similar to Mixins, they can be considered another viable alternative to object sub-classing.

Classically, Decorators offered the ability to add behaviour to existing classes in a system dynamically. The idea was that the decoration itself wasn't essential to the base functionality of the class, otherwise it would be baked into the superclass itself. They can be used to modify existing systems where we wish to add additional features to objects without the need to heavily modify the underlying code using them.

A common reason why developers use them is their applications may contain features requiring a large quantity of distinct types of object. Imagine having to define hundreds of different object constructors for say, a JavaScript game.

The object constructors could represent distinct player types, each with differing capabilities. If we then factored in capabilities, imagine having to create sub-classes for each combination of capability type e.

This isn't very practical and certainly isn't manageable when we factor in a growing number of different abilities. The Decorator pattern isn't heavily tied to how objects are created but instead focuses on the problem of extending their functionality. Rather than just relying on prototypal inheritance, we work with a single base object and progressively add decorator objects which provide the additional capabilities. The idea is that rather than sub-classing, we add decorate properties or methods to a base object so it's a little more streamlined.

Adding new attributes to objects in JavaScript is a very straight-forward process so with this in mind, a very simplistic decorator may be implemented as follows:. This type of simplistic implementation is functional, but it doesn't really demonstrate all of the strengths Decorators have to offer. For this, we're first going to go through my variation of the Coffee example from an excellent book called Head First Design Patterns by Freeman, Sierra and Bates, which is modeled around a Macbook download.

In the above example, our Decorators are overriding the MacBook super-class objects. It's considered a decoration as the original Macbook objects constructor methods which are not overridden e.

There isn't really a defined interface in the above example and we're shifting away the responsibility of ensuring an object meets an interface when moving from the creator to the receiver. This particular variation of the Decorator pattern is provided for reference purposes.

If finding it overly complex, I recommend opting for one of the simpler implementations covered earlier. PJDP describes the Decorator as a pattern that is used to transparently wrap objects inside other objects of the same interface. An interface is a way of defining the methods an object should have, however, it doesn't actually directly specify how those methods should be implemented.

So, why would we use an interface in JavaScript? The idea is that they're self-documenting and promote reusability. In theory, interfaces also make code more stable by ensuring changes to them must also be made to the objects implementing them. In the above, Interface. The biggest problem with interfaces is that, as there isn't built-in support for them in JavaScript, there is a danger of us attempting to emulate a feature of another language that may not be an ideal fit. Lightweight interfaces can be used without a great performance cost however and we will next look at Abstract Decorators using this same concept.

To demonstrate the structure of this version of the Decorator pattern, we're going to imagine we have a superclass that models a Macbook once again and a store that allows us to "decorate" our Macbook with a number of enhancements for an additional fee. Now if we were to model this using an individual sub-class for each combination of enhancement options, it might look something like this:.

This would be an impractical solution as a new subclass would be required for every possible combination of enhancements that are available. As we would prefer to keep things simple without maintaining a large set of subclasses, let's look at how decorators may be used to solve this problem better. Rather than requiring all of the combinations we saw earlier, we should simply have to create five new decorator classes.

Methods that are called on these enhancement classes would be passed on to our Macbook class. In our next example, decorators transparently wrap around their components and can interestingly be interchanged as they use the same interface. To make it easier for us to add as many more options as needed later on, an Abstract Decorator class is defined with default methods required to implement the Macbook interface, which the rest of the options will sub-class.

Abstract Decorators ensure that we can decorate a base class independently with as many decorators as needed in different combinations remember the example earlier? What's happening in the above sample is that the Macbook Decorator accepts an object a Macbook to use as our base component.

It's using the Macbook interface we defined earlier and for each method is just calling the same method on the component. We can now create our option classes for what can be added, just by using the Macbook Decorator. What we're doing here is overriding the addCase and getPrice methods that need to be decorated and we're achieving this by first calling these methods on the original macbook and then simply appending a string or numeric value e.

As there's been quite a lot of information presented in this section so far, let's try to bring it all together in a single example that will hopefully highlight what we have learned.

As decorators are able to modify objects dynamically, they're a perfect pattern for changing existing systems. Occasionally, it's just simpler to create decorators around an object versus the trouble of maintaining individual sub-classes for each object type.

This makes maintaining applications that may require a large number of sub-classed objects significantly more straight-forward. A functional version of this example can be found on JSBin. As with other patterns we've covered, there are also examples of the Decorator pattern that can be implemented with jQuery.

In the following example, we define three objects: The aim of the task is to decorate the defaults object with additional functionality found in options settings. We must:. Developers enjoy using this pattern as it can be used transparently and is also fairly flexible - as we've seen, objects can be wrapped or "decorated" with new behavior and then continue to be used without needing to worry about the base object being modified.

In a broader context, this pattern also avoids us needing to rely on large numbers of subclasses to get the same benefits. There are however drawbacks that we should be aware of when implementing the pattern. If poorly managed, it can significantly complicate our application architecture as it introduces many small, but similar objects into our namespace. The concern here is that in addition to becoming hard to manage, other developers unfamiliar with the pattern may have a hard time grasping why it's being used.

Sufficient commenting or pattern research should assist with the latter, however as long as we keep a handle on how widespread we use the decorator in our applications we should be fine on both counts. The Flyweight pattern is a classical structural solution for optimizing code that is repetitive, slow and inefficiently shares data. It aims to minimize the use of memory in an application by sharing as much data as possible with related objects e. The pattern was first conceived by Paul Calder and Mark Linton in and was named after the boxing weight class that includes fighters weighing less than lb.

The name Flyweight itself is derived from this weight classification as it refers to the small weight memory footprint the pattern aims to help us achieve. In practice, Flyweight data sharing can involve taking several similar objects or data constructs used by a number of objects and placing this data into a single external object. We can pass through this object to those depending on this data, rather than storing identical data across each one.

There are two ways in which the Flyweight pattern can be applied.

Related Post: TEKNISI LAPTOP PDF

The first is at the data-layer, where we deal with the concept of sharing data between large quantities of similar objects stored in memory. The second is at the DOM-layer where the Flyweight can be used as a central event-manager to avoid attaching event handlers to every child element in a parent container we wish to have some similar behavior.

As the data-layer is where the flyweight pattern is most used traditionally, we'll take a look at this first. For this application, there are a few more concepts around the classical Flyweight pattern that we need to be aware of. In the Flyweight pattern there's a concept of two states - intrinsic and extrinsic.

Intrinsic information may be required by internal methods in our objects which they absolutely cannot function without. Extrinsic information can however be removed and stored externally. Objects with the same intrinsic data can be replaced with a single shared object, created by a factory method. This allows us to reduce the overall quantity of implicit data being stored quite significantly. The benefit of this is that we're able to keep an eye on objects that have already been instantiated so that new copies are only ever created should the intrinsic state differ from the object we already have.

We use a manager to handle the extrinsic states. How this is implemented can vary, but one approach to this to have the manager object contain a central database of the extrinsic states and the flyweight objects which they belong to. Our first look at Flyweights in code is my JavaScript implementation of the Java sample of the Flyweight pattern from Wikipedia http: We will be making use of three types of Flyweight components in this implementation, which are listed below:.

Flyweight corresponds to an interface through which flyweights are able to receive and act on extrinsic states Concrete Flyweight actually implements the Flyweight interface and stores intrinsic state.

Concrete Flyweights need to be sharable and capable of manipulating state that is extrinsic Flyweight Factory manages flyweight objects and creates them too.

It makes sure that our flyweights are shared and manages them as a group of objects which can be queried if we require individual instances. If an object has been already created in the group it returns it, otherwise it adds a new object to the pool and returns it.

Flyweight CoffeeFlavor: Concrete Flyweight CoffeeOrderContext: Helper CoffeeFlavorFactory: Flyweight Factory testFlyweight: Utilization of our Flyweights. Duck punching allows us to extend the capabilities of a language or solution without necessarily needing to modify the runtime source. As this next solution requires the use of a Java keyword implements for implementing interfaces and isn't found in JavaScript natively, let's first duck punch it.

We can use this to patch the lack of an implements keyword by having a function inherit an interface explicitly. Below, CoffeeFlavor implements the CoffeeOrder interface and must contain its interface methods in order for us to assign the functionality powering these implementations to an object. Next, let's continue our look at Flyweights by implementing a system to manage all of the books in a library.

The important meta-data for each book could probably be broken down as follows:. We'll also require the following properties to keep track of which member has checked out a particular book, the date they've checked it out on as well as the expected date of return.

Each book would thus be represented as follows, prior to any optimization using the Flyweight pattern:. This probably works fine initially for small collections of books, however as the library expands to include a larger inventory with multiple versions and copies of each book available, we may find the management system running slower and slower over time. Using thousands of book objects may overwhelm the available memory, but we can optimize our system using the Flyweight pattern to improve this.

We can now separate our data into intrinsic and extrinsic states as follows: Effectively this means that only one Book object is required for each combination of book properties.

The following single instance of our book meta-data combinations will be shared among all of the copies of a book with a particular title. As we can see, the extrinsic states have been removed. Everything to do with library check-outs will be moved to a manager and as the object data is now segmented, a factory can be used for instantiation. Let's now define a very basic factory. What we're going to have it do is perform a check to see if a book with a particular title has been previously created inside the system; if it has, we'll return it - if not, a new book will be created and stored so that it can be accessed later.

This makes sure that we only create a single copy of each unique intrinsic piece of data:. Next, we need to store the states that were removed from the Book objects somewhere - luckily a manager which we'll be defining as a Singleton can be used to encapsulate them. Combinations of a Book object and the library member that's checked them out will be called Book records. Our manager will be storing both and will also include checkout related logic we stripped out during our flyweight optimization of the Book class.

The result of these changes is that all of the data that's been extracted from the Book class is now being stored in an attribute of the BookManager singleton BookDatabase - something considerably more efficient than the large number of objects we were previously using. Methods related to book checkouts are also now based here as they deal with data that's extrinsic rather than intrinsic. This process does add a little complexity to our final solution, however it's a small concern when compared to the performance issues that have been tackled.

Data wise, if we have 30 copies of the same book, we are now only storing it once. Also, every function takes up memory.

The best free JavaScript resources

With the flyweight pattern these functions exist in one place on the manager and not on every object, thus saving on memory use. For the above-mentioned flyweight unoptimized version we store just link to the function object as we used Book constructor's prototype but if it was implemented in other way, functions would be created for every book instance. The DOM Document Object Model supports two approaches that allow objects to detect events - either top down event capture or bottom up event bubbling.

In event capture, the event is first captured by the outer-most element and propagated to the inner-most element. In event bubbling, the event is captured and given to the inner-most element and then propagated to the outer-elements.

One of the best metaphors for describing Flyweights in this context was written by Gary Chisholm and it goes a little like this:.

Try to think of the flyweight in terms of a pond. A fish opens its mouth the event , bubbles rise to the surface the bubbling a fly sitting on the top flies away when the bubble reaches the surface the action. In this example we can easily transpose the fish opening its mouth to a button being clicked, the bubbles as the bubbling effect and the fly flying away to some function being run.

Bubbling was introduced to handle situations where a single event e. Where this happens, event bubbling executes event handlers defined for specific elements at the lowest level possible. From there on, the event bubbles up to containing elements before going to those even higher up. For our first practical example, imagine we have a number of similar elements in a document with similar behavior executed when a user-action e. Normally what we do when constructing our own accordion component, menu or other list-based widget is bind a click event to each link element in the parent container e.

Instead of binding the click to multiple elements, we can easily attach a Flyweight to the top of our container which can listen for events coming from below.

These can then be handled using logic that is as simple or complex as required. As the types of components mentioned often have the same repeating markup for each section e.

Oh, and thanks to David Engfer for the joke. Disadvantages The disadvantages of the Module pattern are that as we access both public and private members differently, when we wish to change visibility, we actually have to make changes to each place the member was used.

We also can't access private members in methods that are added to the object at a later point. That said, in many cases the Module pattern is still quite useful and when used correctly, certainly has the potential to improve the structure of our application. Other disadvantages include the inability to create automated unit tests for private members and additional complexity when bugs require hot fixes.

It's simply not possible to patch privates. Instead, one must override all public methods which interact with the buggy privates.

Developers can't easily extend privates either, so it's worth remembering privates are not as flexible as they may initially appear. For further reading on the Module pattern, see Ben Cherry's excellent in-depth article on it. The Revealing Module pattern came about as Heilmann was frustrated with the fact that he had to repeat the name of the main object when we wanted to call one public method from another or access public variables.

The result of his efforts was an updated pattern where we would simply define all of our functions and variables in the private scope and return an anonymous object with pointers to the private functionality we wished to reveal as public. It also makes it more clear at the end of the module which of our functions and variables may be accessed publicly which eases readability. Disadvantages A disadvantage of this pattern is that if a private function refers to a public function, that public function can't be overridden if a patch is necessary.

This is because the private function will continue to refer to the private implementation and the pattern doesn't apply to public members, only to functions. Public object members which refer to private variables are also subject to the no-patch rule notes above.

As a result of this, modules created with the Revealing Module pattern may be more fragile than those created with the original Module pattern, so care should be taken during usage. The Singleton Pattern The Singleton pattern is thus known because it restricts instantiation of a class to a single object. Classically, the Singleton pattern can be implemented by creating a class with a method that creates a new instance of the class if one doesn't exist.

In the event of an instance already existing, it simply returns a reference to that object. Singletons differ from static classes or objects as we can delay their initialization, generally because they require some information that may not be available during initialization time.

They don't provide a way for code that is unaware of a previous reference to them to easily retrieve them. This is because it is neither the object or "class" that's returned by a Singleton, it's a structure. Think of how closured variables aren't actually closures - the function scope that provides the closure is the closure.

In JavaScript, Singletons serve as a shared resource namespace which isolate implementation code from the global namespace so as to provide a single point of access for functions.

What makes the Singleton is the global access to the instance generally through MySingleton. This is however possible in JavaScript.

In the GoF book, the applicability of the Singleton pattern is described as follows: There must be exactly one instance of a class, and it must be accessible to clients from a well-known access point. When the sole instance should be extensible by subclassing, and clients should be able to use an extended instance without modifying their code.

The second of these points refers to a case where we might need code such as: mySingleton. FooSingleton above would be a subclass of BasicSingleton and implement the same interface. Why is deferring execution considered important for a Singleton? It is important to note the difference between a static instance of a class object and a Singleton: whilst a Singleton can be implemented as a static instance, it can also be constructed lazily, without the need for resources nor memory until this is actually needed.

If we have a static object that can be initialized directly, we need to ensure the code is always executed in the same order e. Both Singletons and static objects are useful but they shouldn't be overused - the same way in which we shouldn't overuse other patterns. In practice, the Singleton pattern is useful when exactly one object is needed to coordinate others across a system. They're often an indication that modules in a system are either tightly coupled or that logic is overly spread across multiple parts of a codebase.

Singletons can be more difficult to test due to issues ranging from hidden dependencies, the difficulty in creating multiple instances, difficulty in stubbing dependencies and so on.

Miller Medeiros has previously recommended this excellent article on the Singleton and its various issues for further reading as well as the comments to this article, discussing how Singletons can increase tight coupling. I'm happy to second these recommendations as both pieces raise many important points about this pattern that are also worth noting. The Observer Pattern The Observer is a design pattern where an object known as a subject maintains a list of objects depending on it observers , automatically notifying them of any changes to state.

When a subject needs to notify observers about something interesting happening, it broadcasts a notification to the observers which can include specific data related to the topic of the notification.

When we no longer wish for a particular observer to be notified of changes by the subject they are registered with, the subject can remove them from the list of observers. It's often useful to refer back to published definitions of design patterns that are language agnostic to get a broader sense of their usage and advantages over time.

The definition of the Observer pattern provided in the GoF book, Design Patterns: Elements of Reusable Object-Oriented Software, is: "One or more observers are interested in the state of a subject and register their interest with the subject by attaching themselves.

When something changes in our subject that the observer may be interested in, a notify message is sent which calls the update method in each observer. When the observer is no longer interested in the subject's state, they can simply detach themselves. The update functionality here will be overwritten later with custom behaviour. See below for inline comments on what these components do in the context of our example. Whilst very similar, there are differences between these patterns worth noting.

The Observer pattern requires that the observer or object wishing to receive topic notifications must subscribe this interest to the object firing the event the subject. This event system allows code to define application specific events which can pass custom arguments containing values needed by the subscriber. The idea here is to avoid dependencies between the subscriber and publisher.

This differs from the Observer pattern as it allows any subscriber implementing an appropriate event handler to register for and receive topic notifications broadcast by the publisher. How are you doing today? Rather than single objects calling on the methods of other objects directly, they instead subscribe to a specific task or activity of another object and are notified when it occurs. They also help us identify what layers containing direct relationships which could instead be replaced with sets of subjects and observers.

This effectively could be used to break down an application into smaller, more loosely coupled blocks to improve code management and potentials for re-use.Whilst some of the patterns covered in this book were implemented based on personal experience, many of them have been previously identified by the JavaScript community.

As the data-layer is where the flyweight pattern is most used traditionally, we'll take a look at this first. The Superhero constructor creates an object which descends from Person.

Below we can see an example of a very simplistic model implemented using Backbone. The result of his efforts was an updated pattern where we would simply define all of our functions and variables in the private scope and return an anonymous object with pointers to the private functionality we wished to reveal as public.

Variables can't technically be declared as being public nor private and so we use function scope to simulate this concept.