03.09.2015 Views

Design Patterns

Download - Assembla

Download - Assembla

SHOW MORE
SHOW LESS
  • No tags were found...

You also want an ePaper? Increase the reach of your titles

YUMPU automatically turns print PDFs into web optimized ePapers that Google loves.

CHAPTER 17 ■ THE CHAIN OF RESPONSIBILITY PATTERN 259<br />

Let’s add three methods to the interface: addTag will add a tag to the object it is called on<br />

and to all of its child objects; getPhotosWithTag will return an array of all of the photos that<br />

have a certain tag; and getAllLeaves can be called on any composite to get an array of all of its<br />

leaf nodes. Calling this method on a leaf node just returns an array consisting of itself. We will<br />

start with addTag because it is the simplest:<br />

/* DynamicGallery class. */<br />

var DynamicGallery = function(id) { // implements Composite, GalleryItem<br />

this.children = [];<br />

this.tags = [];<br />

this.element = document.createElement('div');<br />

this.element.id = id;<br />

this.element.className = 'dynamic-gallery';<br />

}<br />

DynamicGallery.prototype = {<br />

...<br />

addTag: function(tag) {<br />

this.tags.push(tag);<br />

for(var node, i = 0; node = this.getChild(i); i++) {<br />

node.addTag(tag);<br />

}<br />

},<br />

...<br />

};<br />

/* GalleryImage class. */<br />

var GalleryImage = function(src) { // implements Composite, GalleryItem<br />

this.element = document.createElement('img');<br />

this.element.className = 'gallery-image';<br />

this.element.src = src;<br />

this.tags = [];<br />

}<br />

GalleryImage.prototype = {<br />

...<br />

addTag: function(tag) {<br />

this.tags.push(tag);<br />

},<br />

...<br />

};<br />

We add an array called tags to both the composite and the leaf classes. This array will<br />

hold the strings that represent the tags. In the leaf class’s addTag method, you simply push the<br />

string passed in as the argument to the tags array. In the composite class’s method, you do<br />

that, as well as pass the request down the hierarchy, just like any other normal composite<br />

method. Despite the fact that giving a tag to a composite object effectively gives the tag to all<br />

of its child objects, you must still add the tag to each child object. A search can be started at

Hooray! Your file is uploaded and ready to be published.

Saved successfully!

Ooh no, something went wrong!