I wanted to implement a basic Graph structure that could later be extended to more specific types of Graph (Dialogue, Behavior...) which would each also need specific types of nodes which would derive from a Node base class.
My Graph base class looks like this right now
public abstract class Graph {
private Dictionary<Node, List<Node>> adjList;
public abstract void AddNode(Node node);
public abstract void RemoveNode(Node node);
public abstract void AddEdge(Node node, Node destNode);
public abstract void RemoveEdge(Node node, Node destNode);
}
My problem is that I would have to typecheck in the implementation of those methods to prevent users from adding, for example, a DialogueNode to a QuestGraph. Are there any design patterns to fix this? Or should I just do without a base class and write some code multiple times?
My problem is that I would have to typecheck in the implementation of those methods to prevent users from adding, for example, a DialogueNode to a QuestGraph.
You could define an abstract generic class and specify a specific Node subtype for each implementation.
For example in Java:
public abstract class Graph<T extends Node> {
private Dictionary<T, List<T>> adjList;
public abstract void AddNode(T node);
public abstract void RemoveNode(T node);
public abstract void AddEdge(T node, T destNode);
public abstract void RemoveEdge(T node, T destNode);
}
And the QuestGraph
subclass could be like:
public class QuestGraph extends Graph<QuestNode> {
public void AddNode(QuestNode node){...}
public void RemoveNode(QuestNode node){...}
// And so for ...
}
Are there any design patterns to fix this?
Design patterns don't enforce that kind of rules and in a general way is not designed to limit polymorphism abilities.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.