How do you handle or what pattern do you use for a object that occurs all through a tree but is unique? I don't want to create this object every time I need one because every instance of this object is identical and all I need is a reference to that object.
A classic example would be an empty node in a binary tree. We use this empty node all through the tree, but they are identical so all we need is one empty node and many references to it. How do I manage that in Java?
Its a Btree and all the nodes are immutable. I'm basically starting with the concept that the Btree contains Nodes and Nodes is abstract with two subclasses Empty and Node. It worked great until I realized that creating a new instance of Empty was wasteful and I should have one instance of Empty which is referenced many times.
I found a solution or at least a starting point. I created a Btree class which is basically a wrapper that contains a final instance of the empty node and an inner class which contains the functionality for a Btree. It works, well it creates one empty node that is shared across all nodes.
I'll have to do a lot more contemplating/reading before I settle on a real solution.
Gerard Gauthier wrote:It's surprising how straightforward the code became when I pushed the functionality down to the nodes.
Yeah, that's how object-oriented design works. A Node should know how to add a new Node underneath it, for example, rather than having something outside the class be responsible for that.
Just a comment: I looked at your code for quite a while trying to understand why Node was a subclass of Nodes. To me a Nodes object should represent a collection of nodes, and it took a while before I realized that your Nodes class doesn't do that. Instead it's an abstract class which specifies what methods a class should implement if it's supposed to represent a node. So I would have called it AbstractNode.
Gerard Gauthier wrote:I guess I should've included the Btree class in the post.
Yes, that would have helped. I looked up B-trees and it seems to me that you are designing a binary search tree. It wasn't obvious to me why any nodes in such a tree would be empty. Which is why I wasn't surprised that you didn't use the Empty class anywhere.
Edit: Never mind, I just scrolled back and read your explanation of that. Now I'm confused by the fact that your Node and Empty classes are immutable, but I expect the Btree class would explain that.