By paddloPayday loans

Archive

Archive for the ‘JavaScript’ Category

From ActionScript 3.0 to JavaScript Chain of Responsibility: Part II The Help Desk

corjs

JavaScript can do Design Patterns

A JavaScript Chain of Responsibility

I’ve always liked JavaScript, but after going through this last project of creating a design pattern with JS, I find that I like ActionScript 3.0 even more than I did before. The biggest problems that I encountered with JavaScript is that different users slipped in different frameworks (e.g., Prototype.js) and didn’t seem to mention it. My goal was to create a JS design pattern with pure unadulterated JavaScript—not using JQuery, JSon or some other helpful framework. Now, don’t get me wrong—I appreciate a good framework as much as the next guy. However, when I’m trying to create a design pattern for a general language like JavaScript, I’d rather not have to have readers run out and get one framework or another. I wanted this to work with Plain Vanilla JavaScript. So that’s what you’re going to get.

To get started, I took a look at some articles on JavaScript and classes, inheritance and OOP in general. Then I looked at some implementations of JavaScript with a Chain of Responsibility pattern. A lot of them didn’t make a bit of sense, and that’s when I realized that they were slipping in different “helpers,” and so I went back to the most basic JavaScript OOP I knew of–the 1999 book, JavaScript Objects by Nakhimovsky and Myers. Starting there, I pretty much followed that Chain of Responsibility pattern we had in Part I of this two-part series. However, instead of a mobile browser detector, I created a “Help Desk.”

Before continuing, take a look at the “Help Desk” app made with the JS CoR:

helpdesk

Figure 1: JavaScript Chain of Responsibility Help Desk

Inheritance is a ‘IS-A’

First I made an abstract Handler class using a single concrete and single abstract method. It seemed to me that classes in JavaScript could be abstract simply by adding a method with no content. I came up with the following class:

?View Code JAVASCRIPT
1
2
3
4
5
6
7
8
9
10
11
12
13
14
function Handler()
{ 
	//Handler 'abstract class'
} 
 
Handler.prototype.setSuccessor=function(successor)
{ 
	this.successor=successor;
} 
 
Handler.prototype.handleRequest=function(req)
{ 
	//Abstract method overridden in concrete implementation
}

I realize that it looks strange compared to more mature OOP languages like ActionScript 3.0 (not to mention Java and C++), but remember, I’m using pure native JavaScript. You create the class by the simple expedient of a function. Then, I create the methods for the class by using a Class.prototype. The class Handler now has the setSuccessor and handleRequest methods, just as we had in the ActionScript 3.0 version. So, while it looks a little goofy for creating classes and their methods and properties, that’s how it’s done.

So far so good, and it’s not rocket science. However, the next part gets a little dicey and may pop a few brain nodes. When you extend a class in JavaScript, you first instantiate the parent class. As we all know, you do not instantiate abstract classes or any other interface. They’re extended or implemented. However, that’s not the case with JavaScript. Take a look at this first child class of Handler:

?View Code JAVASCRIPT
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
//AS3DP inherits handler
AS3DP.prototype= new Handler();
 
function AS3DP()
{
	//AS3DP 'class'
}
 
AS3DP.prototype.handleRequest=function(req)
{
	this.req=req;
	if(this.req=="as3dp")
	{
		document.write("Naturally you want to read <em>ActionScript 3.0 Design Patterns</em> and visit our blog at as3dp.com.");
	}
	else if(this.successor != null)
	{
		document.write("Not AS3DP<br/>");
		this.successor.handleRequest(this.req);
	}
}

If you recall, basic design pattern principles, a child class “Is-A” parent class. When a JavaScript object (like AS3DP) is instantiated, it is done by declaring itself as a new Handler(). So rather than becoming a child of the parent through extension, JavaScript uses the object prototype to declare itself as an instance of the parent. It’s actually easier to see that a child class indeed “Is-A” parent because the prototype declares itself as such.

As we have seen, the methods and properties have been created outside of the class constructors. Instead of being in the class, they are in the prototype. For now, you can think of the class as the “concept of an object” and it creates and stores the properties for that concept in prototypes. So, knowing that, we can create the rest of the concrete handlers:

?View Code JAVASCRIPT
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
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
//Game inherits Handler
Game.prototype= new Handler();
 
function Game()
{
	//Game 'class'
}
 
Game.prototype.handleRequest=function(req)
{
	this.req=req;
	if(this.req=="game")
	{
		document.write("As the states change, you want a good state machine like the State Design Pattern.");
	}
	else if(this.successor != null)
	{
		document.write("Not State pattern<br/>");
		this.successor.handleRequest(this.req);
	}
}
 
//Algorithm inherits Handler
Algorithm.prototype= new Handler();
 
function Algorithm()
{
	//Algorithm 'class'
}
 
Algorithm.prototype.handleRequest=function(req)
{
	this.req=req;
	if(this.req=="algorithm")
	{
		document.write("The Strategy Design Pattern lets you access different algorithms directly without having to use conditional statements!");
	}
	else if(this.successor != null)
	{
		document.write("Not Strategy pattern<br/>");
		this.successor.handleRequest(this.req);
	}
}
 
//Factory inherits Handler
Factory.prototype= new Handler();
 
function Factory()
{
	//Factory 'class'
}
 
Factory.prototype.handleRequest=function(req)
{
	this.req=req;
	if(this.req=="factory")
	{
		document.write("The Factory Method design pattern will unlink the request to build an object from the actual object creation.");
	}
	else if(this.successor != null)
	{
		document.write("Not Factory<br/>");
		this.successor.handleRequest(this.req);
	}
}
 
//ToInterface inherits Handler
ToInterface.prototype= new Handler();
 
function ToInterface()
{
	//ToInterface 'class'
}
 
ToInterface.prototype.handleRequest=function(req)
{
	this.req=req;
	if(this.req=="tointerface")
	{
		document.write("The first principle is to <em>Program to the interface and not the implementation.</em> When you declare a new object, type it to the object's parent class; not the object itself.");
	}
	else if(this.successor != null)
	{
		document.write("Not Program to Interface<br/>");
		this.successor.handleRequest(this.req);
	}
}
 
//Truth inherits Handler
Truth.prototype= new Handler();
 
function Truth()
{
	//Truth 'class'
}
 
Truth.prototype.handleRequest=function(req)
{
 
	document.write("You know I can't handle the truth! Go visit a muse, a swami, or 3-year old.<br/>");
 
}

As you no doubt have noticed, this Chain of Responsibility implementation is not about mobile devices and their languages. Instead, it’s a “Help Desk” that I think is more typical of what you may actually use a CoR pattern for—either in JavaScript or ActionScript 3.0.

All that’s left is to do with the JavaScript is to create instances of the different handlers and set the chain of successors. The “client” that makes the requests is the HTML5 UI.

?View Code JAVASCRIPT
1
2
3
4
5
6
7
8
9
10
11
12
13
//'Instantiate Concrete Handlers'
var as3dp = new AS3DP();
var game=new Game();
var algorithm=new Algorithm();
var factory=new Factory();
var tointerface=new ToInterface();
var truth=new Truth();
//Set successors
as3dp.setSuccessor(game); 
game.setSuccessor(algorithm); 
algorithm.setSuccessor(factory);
factory.setSuccessor(tointerface);
tointerface.setSuccessor(truth);

You can set up the successors in any way you want except the last one has to be to the Truth class. It has no successor and is meant to be the caboose of the chain. Before going on, place all of the JavaScript into a single file and save it as “HelpDesk.js” and put it in the same folder (directory) as the HTML5 program that follows.

The HTML5 Client

Like most work with JavScript, the UI is in HTML. This is no different. All it does is to call the top of the chain (AS3DP instance) and make a request. All of the requests look like the following:

onclick=”as3dp.handleRequest(‘algorithm’);

The click handler calls the top of the chain, and the Chain of Responsibility just chugs on through until it finds what you want. Here’s the whole HTML5 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
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
<!DOCTYPE HTML>
<html>
<head>
<style type="text/css">
body {
	font-family:Verdana, Geneva, sans-serif;
	color:#1D232;
	background-color:#dddcc5;
	font-size:12px;
}
h2 {
	font-family:"Arial Black", Gadget, sans-serif;
	font-size:24px;
	text-align:center;
	color:#611427;
}
form {
	color:#6A6A61;
}
h3 {
	background-color:#611427;
	color:#958976;
	font-size:18px;
}
</style>
<script type="text/javascript" src="HelpDesk.js">
</script>
<meta charset="UTF-8">
<title>Billz Help Desk</title>
</head>
 
<body>
<header>
  <h2>Billz Help Desk</h2>
</header>
<article>
<header>
  <h3>&nbsp;Chain of Responsibility: JavaScript</h3>
</header>
<section> This is a simple Chain of Responsibility (CoR) application. Each button represents a different request that the CoR will handle. In this case, the help is in the form of a 'Help Desk' and the CoR finds the appropriate response to the query.<br/>
  <br/>
  <form>
    <input type=button value="Make Request" onclick="as3dp.handleRequest('as3dp');" />
    How do I learn about design patterns for ActionScript 3.0 <br/>
    <input type=button value="Make Request" onclick="as3dp.handleRequest('game');" />
    I'm making a game where states keep changing. What would be a good design pattern for dealing with changing states?<br/>
    <input type=button value="Make Request" onclick="as3dp.handleRequest('algorithm');" />
    My app involves a lot of problem solving with different algorithms? What's a good pattern for dealing with multiple algorithms?<br/>
    <input type=button value="Make Request" onclick="as3dp.handleRequest('factory');" />
    Whenever I create a new object with my Client object, I build up dependencies. Is there a pattern to avoid such dependencies?<br/>
    <input type=button value="Make Request" onclick="as3dp.handleRequest('tointerface');" />
    What is a primary guiding design pattern principle?<br/>
    <input type=button value="Make Request" onclick="as3dp.handleRequest('truth');" />
    I want to know the truth!<br/>
  </form>
</section>
<br/>
<section>The CoR pattern works sequentially so that as it moves through the chain, you can see each rejected attempt to find the correct handler. (Normally, you wouldn't see those rejected handlers.) It is a very easy pattern to update and add additional handlers.</section>
</article>
</body>
</html>

So, now you’re all set to use JavaScript for design patterns. The plain vanilla JS has limitations doing OOP, but you can harness it and bend it to your OOP will. The many different frameworks that work in conjunction with basic JavaScript will make it look more like an OOP language, but you can get by without. There’s a lot to be done with even the most unadorned JavaScript, and I tested the app on an iPhone, and it works fine. However, I’ll bet that several of you can find better ways to handle either the JavaScript or HTML5 (or both) with design patterns, and we’d like to hear from you. Naturally, if you have a favored framework that makes OOP work more efficient, let us know—even better send a design pattern example.

Share

From ActionScript 3.0 to JavaScript Chain of Responsibility: Part I

December 26, 2011 2 comments

After Mom, Ask Dad, and then the Dog

After Mom, Ask Dad, and then the Dog

Just Follow the Chain of Responsibility

To get started on the quest to see whether useful design patterns can be created with JavaScript, I thought it’d be a good idea to go from the known to the unknown. In this case, those familiar with this blog know ActionScript 3.0 design patterns, and the unknown (for some at least) is JavaScript. Well, I suppose just about everyone who reads this blog knows something about JavaScript, but several may not have been involved with either JavaScript OOP or design patterns. By creating an ActionScript 3.0 app using a pattern and then going through the app step-by-step, readers may be better able to understand how we might approach design patterns using JavaScript. I decided to use the Chain of Responsibility (CoR) pattern to go through the types of mobile operating systems that we examined in the previous post. In this way, we can create something both familiar and practical.

Every time I use the Chain of Responsibility pattern, I feel that I’m swatting a fly with a weapon of mass destruction. I see all of these classes, and I’m thinking that I could have done the same thing with a switch statement or something even slicker. Then I need to remind myself why I’d use the CoR in the first place.

The Chain of Responsibility separates the handling of an event from the request to handle it.

In a broader context, this allows the developer to make changes to either the request or the handling of the event without disrupting some other part of the program. It’s quite simple as well. Just imagine several people lined up with different kinds of expertise and/or authority. A request is issued, and once it reaches the person with the right expertise or authority, it is handled. The request is separated from the way it will be handled. That’s up to the expert. Figure 1 shows the class design:

<em><strong>Figure 1: </strong> Chain of Responsibility Pattern</em>

Figure 1: Chain of Responsibility Pattern

Getting Started with CoR

For details about ways to setup and use CoR see our original discussion . The focal points are in the following:

  • An interface (an abstract class or interface) establishes a handler operation
  • Each request handler has a separate class derived from the handler interface
  • Each handler class has a successor which is another handler class
  • The last handler in the chain has no successor
  • As soon as a handler can handle the request, the chain stops and the handler takes care of the request.

You may be thinking that this is not very efficient since it requires a sequential path. We’ve considered ways to get around a sequence (see our posts on Skip Lists), but for now we’ll stick with the traditional CoR and use a sequential search through the list of handlers.

The Chain of Mobile Operating Systems

This CoR simulates finding one of several types of mobile OS. Given the type of OS, it looks for ways to handle each one optimally. In the JavaScript version of this, we want to have it select a CSS file or another JS file to best use the kind of mobile device involved. The concrete handler classes are the objects used to deal with whatever requirements are necessary. In the example, each handler simply traces out “Set up for xxOS,” where “xx” is the found mobile OS. It also traces out which handlers were rejected so that you can better see how the chain works. Since Android is at the top of the chain, you see no rejections, while Windows CE at the bottom of the chain displays the whole chain.

It might be helpful if you take a look at the whole concept of Linked Lists. The Chain of Responsibility is something like a linked list, but instead of linking lists, it links handlers.

The Client class makes the initial request and sets up a simple requesting UI for testing the application. It makes requests using a string. I just used the lowercase ID of the main mobile OS types as the “request-to-handle.” After making the request, the “chain” takes over. In this example the top of the chain is the Android, but it could be any of the others as well. The developer has complete control over the sequence.

?View Code ACTIONSCRIPT
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
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
package
{
	import flash.display.Sprite;
	import flash.events.MouseEvent;
	import fl.controls.Button;
	import fl.controls.TextInput;
	import fl.controls.Label;
	import flash.text.TextFieldAutoSize;
 
	public class Client extends Sprite
	{
		//Handlers + Request
		private var android:Handler= new Android();
		private var iphone:Handler= new IPhone();
		private var blackberry:Handler= new Blackberry();
		private var series60:Handler=new Series60();
		private var windowsce:Handler=new WindowsCE();
		private var cannothandle:Handler=new CannotHandle();
 
		//UI
		private var btn:Button=new Button();
		private var iput:TextInput=new TextInput();
		private var lbl:Label=new Label();
 
		public function Client()
		{
			setupChain();
			setupUI();
		}
 
		private function setupChain():void
		{
			//Sequence set up here
			android.SetSuccessor(iphone);
			iphone.SetSuccessor(blackberry);
			blackberry.SetSuccessor(series60);
			series60.SetSuccessor(windowsce);
			windowsce.SetSuccessor(cannothandle);
		}
 
		private function setupUI():void
		{
			//This simulates getting the mobile OS from the using system
			lbl.autoSize = TextFieldAutoSize.LEFT;
			lbl.text="Enter name of mobile device: (Use lower case.)";
			lbl.x=50,lbl.y=30;
			addChild(lbl);
			btn.x=50, btn.y=75;
			btn.label="Start the chain";
			btn.addEventListener(MouseEvent.CLICK,requestOS);
			addChild(btn);
			iput.x=50,iput.y=50;
			addChild(iput);
		}
 
		private function requestOS(e:MouseEvent)
		{
			android.HandleRequest(iput.text);
		}
	}
}

For the end of the chain, I added a “CannotHandle” class that extends the Handler interface. This functions something like a default option in a switch statement. If none of the handlers can handle the request, you need to provide the user with some kind of feedback.
Read more…

Share

Can JavaScript Create Design Patterns?

November 28, 2011 7 comments

Face the Facts: We've got to deal with Mobile

Face the Facts: We've got to deal with Mobile

Ever since Adobe announced that they’d no longer be making a Flash player for mobile devices, I thought that it’d be a good idea to have some kind of filter to distinguish between desktop browsers and mobile ones. On this blog, I’d like to introduce a topic that is related to the continuing efforts to build apps and Web pages with ActionScript 3.0 using OOP and Design Patterns. The topic is a language: JavaScript.

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:

?View Code JAVASCRIPT
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:

  1. Set up a dummy Chain of Responsibility that links the different kinds of responsibilities.
  2. Have each responsibility be actions taken for different kinds of mobile devices or a desktop.
  3. 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.

Share