Sunday, February 22, 2009
Intent: Represent an operation to be performed on the elements of an object structure. Visitor lets you define a new operation without changing the classes of the elements on which it operates.
//Define name space
var Visitor = {};
//The composite of elements
Visitor.ObjectStructure = function(){
var _elements = [];
this.attach = function(element){
_elements.push(element);
};
this.detach = function(element){
for(var i = 0; i < _elements.length; i++){
if(_elements[i] == element) _elements.splice(i, 1);
}
};
this.accept = function(visitor){
_elements.forEach(function(element){
element.accept(visitor);
});
};
};
//The concrete element will follow the same interface
Visitor.ElementA = function(){
this.accept = function(visitor){
visitor.visitElementA(this);
};
//Default operation of 'ElementA'
this.operationA = function(){
console.log('default operation of element A');
};
};
Visitor.ElementB = function(){
this.accept = function(visitor){
visitor.visitElementB(this);
};
//Default operation of 'ElementA'
this.operationB = function(){
console.log('default operation of element B');
};
};
//Visitor will follow the same interface
Visitor.VisistorA = function(){
this.visitElementA = function(elementA){
console.log("elementA is visited by visitorA");
};
this.visitElementB = function(elementA){
console.log("elementB is visited by visitorB");
};
};
Subscribe to:
Post Comments (Atom)
No comments:
Post a Comment