Can JavaScript Create Design Patterns?

Face the Facts: We've got to deal with Mobile
At this point in time I can easily create a script to determine whether a browser is mobile or non-mobile. I want to get to the point where I can put together a Chain of Responsibility pattern so that I have a flexible design for tweaking a specific kind of mobile device (e.g., calling up appropriate CSS). This requires OOP JavaScript, and so I had to revisit my old JavaScript work. One of the best books on both OOP and JavaScript is Javascript Objects: Object Use and Data Manipulation with JavaScript by Alenander Nakhimovsky and Tom Myers published by Wrox in 1998. It was written by a couple of professors at Colgate University and is pitched at a pretty high level that most readers of this blog will appreciate. (You can still get it from Amazon, and it’s a gem to have no matter what language you favor.) Another good book that deals with JavaScript objects is Douglas Crockford’s JavaScript: The Good Parts (O’Reilly, 2008). Crockford understands JavaScript down to the metal and has great explanations and examples.
So the question is:
Can JavaScript handle OOP and Design Patterns?
To find out, I started writing some prototype classes but found I’d have to spend some more time trying to cobble something together that was both reasonable (it maintains the DP value of flexibility, update and reuse) and real (I didn’t want to make a phony DP with hack classes.) However, it didn’t take long to put together a little code that works to filter out both different mobile devices and non-mobile devices. My plan is to take this code and change it so that I can do the same thing with a Chain of Responsibility design pattern. Here’s the code:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 | // JavaScript Document
var sniffer=new Object();
var agentNow=navigator.userAgent.toLowerCase();
sniffer.android=(agentNow.search("android")>=0);
sniffer.series60=(agentNow.search("series60")>=0);
sniffer.iphone=(agentNow.search("iphone")>=0);
sniffer.blackberry=(agentNow.search("blackberry")>=0);
sniffer.windowsce=(agentNow.search("windows ce")>=0);
var counter=0;
var flag=new Object();
flag.nonMobile=true;
for(var mobile in sniffer)
{
if(sniffer[mobile])
{
switch(counter) {
case 0:
document.write("android<br/>");
flag.nonMobile=false;
break;
case 1:
document.write("series60<br/>");
flag.nonMobile=false;
break;
case 2:
document.write("iphone<br/>");
flag.nonMobile=false;
break;
case 3:
document.write("blackberry<br/>");
flag.nonMobile=false;
break;
case 4:
document.write("windows ce<br/>");
flag.nonMobile=false;
break;
}
}
counter++;
}
if(flag.nonMobile)
{
document.write("Non-mobile or unrecognized device.");
document.write("<br/>");
} |
Before you say anything (or think anything), I realize that this code is about as flexible as a rebar (AKA: reinforcing bar), and if you’re into JavaScript, you can think of 10 ways that this can be done better. However, the goal is to see if this can be refactored into a design pattern. Here’s my plan:
- Set up a dummy Chain of Responsibility that links the different kinds of responsibilities.
- Have each responsibility be actions taken for different kinds of mobile devices or a desktop.
- Use JavaScript objects to do the work of the concrete handlers
However, before I get started on this project, I’d really like to hear from you and even better, see what you can do with this challenge. So between now and the next post on this topic, let’s hear from you! Also feel free to add different kinds of mobile devices such as tablets and other phone OSs.
No related posts.

Bill Sanders
You might want to read “Essential JavaScript Design Patterns For Beginners”.
http://addyosmani.com/resources/essentialjsdesignpatterns/book/
I simplified your code a bit. It isn’t the best of examples.
function detectBrowser() { var result = "Non-mobile or unrecognized device."; var match = navigator.userAgent.exec(/android|series60|iphone|blackberry|windows ce/i); if (match !== null) { result = match[0]; } return result } document.write(detectBrowser() + "");Hi Kristof,
Thank you for the code and the “book” on JavaScript and JQuery. The “book” is a little brief, and some of the patterns are actually something other than design patterns, but that’s OK–it’s a starting point. (I believe it was translated from another language into English, and it needs some editing, and I’ll be glad to help out if the author will contact me at williebegoode@att.net — for example in the Factory pattern section, where it notes …applied to the falling situations:…. , the author meant to say, …applied to the following situations…)
As for the refactoring you did–it’s a beautiful, tightly coded piece of work. However, it did not work on some browsers I tested it on. More importantly, we need to see how can it be re-written so that it can be placed into a Chain of Responsibility (CoR) design. If we can work up a CoR example, Addy Osmani can add it to his little book.
Kindest regards,
Bill
Hi Bill,
This 2 books are good :
http://jsdesignpatterns.com/
and
http://www.amazon.com/Pro-JavaScript-Techniques-John-Resig/dp/1590597273 (by the programmer of jQuery)
Patrick
Hi Patrick,
Hey thanks for those two links! I downloaded the source code for the JS DP book, and sure enough they included a CoR pattern, and so I’ll be able to look at it and see if we can incorporate it in creating a little app that will determine what kind of mobile device is in use. I also downloaded the Pro-JS book source code, and it comes with a couple of chapters as well. So if any of you are interested, take a look at the materials for both books.
Let me assure you that I’ve been developing ActionScript 3.0 all along, and over the weekend I developed a matrix navigation system using a State Design Pattern. Very sweet and it is destined to become the base for a game app that I’m working up for play on mobile devices.
Kindest regards,
Bill
Hi Bill,
great article.
I have to implement this kind of device-check (in my case the language is PHP, but DP are a way of thinking)and CoR is a great solution. At the end my ConcreteHandlers will return an Abstract Factory to layout my page.
Es:
DesktopHandler will serve a factory that makes flash-based widgets
MobileHandler will serve a factory that makes html5-based widgets
and so on….
Hi Marco,
That’s exactly the kind of use I was thinking of. With simple operations, a CoR may be a bit much, but having separate classes handle different kinds of events such as widgets or factories as you’re doing would be an idea application.
I’m hoping to do more with JavaScript and ActionScirpt 3 interacting. After all, ActionScript 1 is JavaScript!
Cheers,
Bill