In this section, we show a further example of using virtual class attributes from the domain of graphs. Graphs have many applications. Here we sketch the structure of a graph of cities connected with roads. Such a graph may e.g. be used for tour planning. We also show a very brief sketch of a graph for computer networks connected with cables.
We start by defining a class defining an overall structure of a graph:
class Graph:
class Node(id: var String):<
addEdge(to: ref Node)-> E: ref Edge:<
:::
:::
class Edge(from: ref Node, to: ref Node):<
:::
nodes: obj Set(#Node)
addNode(nm: var String) -> n: ref Node:
:::
display: ...
:::
Class Graph
has the following attributes:
- Two virtual classes
Node
andEdge
representing the nodes and edges of the graph. They will be further extended in subclasses ofGraph
as we shall se below. - An object
nodes
, which contains the set of nodes of a given graph. - A method
addNode
for adding aNode
to a givenGraph
. - A method
display
for displaying the graph.
Class Node
has a method addEdge
for adding an edge from the Node
to a node represented by the parameter to
.
The Node
class has the structure:
class Node(id: var String):<
addEdge(to: ref Node)-> e: ref Edge:<
e := Edge(this(Node),to)
inner(addEdge)
edges.insert(e)
edges: obj Set(#Edge)
display:< ...
displayEdges:< ...
- The parameter
id
represents the id/name of theNode
. - The method
addEdge
adds anEdge
to theNode
. - The object
edges
holds all the edges from theNode
. - The method displays the
Node
anddisplayEdges
display the edges of theNode
.
In this simple example, the Edge
class just has a display
method, which invokes inner
.
class Edge(from: ref Node, to: ref Node):<
display:<
inner(display)