views:

1184

answers:

8

I'm a moderately skilled programmer using JavaScript but I am no guru. I know you can do some pretty powerful things with it, I just haven't seen much other than fairly basic DOM manipulation. I'm wondering if people could provide some examples of traditional design pattern concepts such as Factory Method, Singleton, etc using JavaScript. In what cases would these patterns be used for on the web?

A: 

I suspect they can - here's an example of Singleton:

The singleton design pattern in JavaScript

jamting
+2  A: 

The singleton design pattern in JavaScript

Oh my god. I'm speechless.

To OP: yes, of course you can in some sense, but some patterns, as you're used to them, are not as visible, as in Java. For example, singleton would simply be an object:

var singleton = {
    sayHello: function() {
       alert("Hello!")
    }
};

[edit] factory: http://en.wikipedia.org/w/index.php?title=Factory_method_pattern&oldid=229607677#JavaScript (edited the link to point to the version I originally linked to, since the version as of 2010-06-02 is convoluted.)

Nickolay
A: 

Sure they can. Here's a book on the subject:
Pro JavaScript Design Patterns
Here's an example of the Factory pattern:
Factory pattern in Javascript

Jonathan Rauch
+6  A: 

Nickolay touched on this, but design patterns are not consistent between languages that have drastic differences. I have read before (and agree with) that a design pattern is often a sign of missing features in the language.

As a perfect example, the "Factory" pattern is completely unnecessary in some languages, Ruby as the example I am thinking of (because object construction is just a method on the Class instance):

# create a factory for MyObject
my_factory = MyObject
instance_1 = my_factory.new

# change the factory to another class
my_factory = MyOtherObject
instance_2 = my_factory.new

Whenever you are applying a design pattern to a different language than it was initially developed for, make sure you consider if it is REALLY necessary, and what ways you might be able to improve it with the new language features available. Design patterns are just a guide, you should always consider if the use you intend really needs the pattern, or if it can be adopted in a better way in your case.

Mike Stone
+6  A: 

I just wanted to add my favorite JavaScript pattern that I learned from Pro JavaScript Design Patterns which Jonathan Rauch already recommended.

It is the namespace singleton pattern. Basically, you create namespaces via singletons which allow you to hide methods and variables from external use. The hidden/exposed methods are actually hidden because they are defined within the closure.

var com = window.com || {};
com.mynamespace = com.mynamespace || {};
com.mynamespace.newpackage = (function() {
    var myPrivateVariable = "hidden";
    var myPublicVariable = "exposed";

    function myPrivateMethod() {
        return "also hidden";
    }

    function myPublicMethod() {
        return "also exposed";
    }

    return {
        myPublicMethod: myPublicMethod,
        myPublicVariable: myPublicVariable
    };
})();
Mike Stone
Should it be `com.mynamespace.newpackage = (function () { ... }())`? Just curious because JSLint complains. :)
Brian M. Hunt
@Brian M. Hunt: I've always seen it as the way I wrote it, but your way seems to work in Chrome and Firefox, dunno about IE and others though. Regardless, some parens are needed, otherwise the parens applying the function are reported as syntax errors.
Mike Stone
+2  A: 

I have recently used Bernie's Better Animation Class that makes extensive use of the Strategy Design Pattern. Bernie does a great job at describing why the Strategy Pattern should be used but sadly does not explain exactly how the code works. Then again, when using a Design Patterns reference, take a look at the code and comments in animator.js for a good example of how to use the Strategy Pattern.

Example:

// This object controls the progress of the animation 
ex1 = new Animator();
// The Animator's subjects define its behaviour 
ex1.addSubject(updateButton);
function updateButton(value) {
    $('ex1Button').innerHTML = "Progress: " + Math.round(value * 100) + "%";
}

// now click below: each click to the button calls ex1.toggle()
Huppie
A: 

I would like to add in here what I have studied as a group with discussion about design patterns both in C# and JavaScript. What is the fancy thing for me during meeting is that the C# guy write codes in JavaScript and the same thing for the JavaScript guy. After I leave the meeting I try to learn more at home and do blogging in here http://tech.wowkhmer.com/category/Design-Patterns.aspx for both C# and JavaScript.

Vorleak Chy
That's a pity: 404.
Marcel Korpel
A: 

Listen to Justin Diaz talking about design pattern for Javascript. The talk is also based on his book Pro Javascript Techniques mentionned above. The talk is about 45 min at Google I/O

ken