Created
April 24, 2023 05:15
-
-
Save hasithaa/47861aa8f2c8acf4f0e94ef31adf9bb8 to your computer and use it in GitHub Desktop.
Ballerina Object Visitor Pattern
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import ballerina/io; | |
public type Element object { | |
public function accept(Visitor visitor); | |
}; | |
public class ConcreteElementA { | |
*Element; | |
public function accept(Visitor visitor) { | |
visitor.visitConcreteElementA(self); | |
} | |
public function operationA() returns string { | |
return "ConcreteElementA operation"; | |
} | |
}; | |
public class ConcreteElementB { | |
*Element; | |
public function accept(Visitor visitor) { | |
visitor.visitConcreteElementB(self); | |
} | |
public function operationB() returns string { | |
return "ConcreteElementB operation"; | |
} | |
}; | |
public type Visitor object { | |
public function visitConcreteElementA(ConcreteElementA element); | |
public function visitConcreteElementB(ConcreteElementB element); | |
}; | |
public class ConcreteVisitor1 { | |
*Visitor; | |
public function visitConcreteElementA(ConcreteElementA element) { | |
io:println("ConcreteVisitor1: ", element.operationA()); | |
} | |
public function visitConcreteElementB(ConcreteElementB element) { | |
io:println("ConcreteVisitor1: ", element.operationB()); | |
} | |
}; | |
public function main() { | |
Element[] elements = [new ConcreteElementA(), new ConcreteElementB()]; | |
Visitor visitor1 = new ConcreteVisitor1(); | |
clientCode(elements, visitor1); | |
} | |
function clientCode(Element[] elements, Visitor visitor) { | |
foreach var element in elements { | |
element.accept(visitor); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment