Last active
April 24, 2023 10:57
-
-
Save hasithaa/5a50ad63dfc2624647a8ceaaaa5dfdcd to your computer and use it in GitHub Desktop.
Record Visitor Pattern
This file contains 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; | |
// Type Nodes | |
type Node record { | |
string kind; | |
string value; | |
}; | |
type NodeA record { | |
*Node; | |
"NodeA" kind = "NodeA"; | |
string value; | |
}; | |
type NodeB record { | |
*Node; | |
"NodeB" kind = "NodeB"; | |
string value; | |
int count; | |
}; | |
// Actual Node vistor Logic | |
function visitNodeA(NodeA node) { | |
io:println("Do something with NodeA", node); | |
} | |
function visitNodeB(NodeB node) { | |
io:println("Do something with NodeB", node); | |
} | |
// Node visitor dispatcher | |
function visit(Node node) returns error? { | |
match node.kind { | |
"NodeA" => { | |
visitNodeA(check node.ensureType()); | |
} | |
"NodeB" => { | |
visitNodeB(check node.ensureType()); | |
} | |
} | |
} | |
public function main() returns error? { | |
Node[] nodes = [ | |
{kind: "NodeA", value: "A"}, | |
{kind: "NodeB", value: "B", "count": 1}, | |
{kind: "NodeA", value: "C"} | |
]; | |
foreach var node in nodes { | |
check visit(node); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment