I have a class RT
modelling a rooted tree (essentially).
Let's say, I have already an instance rt1
holding the following tree:
1
/ \
0 2
Now, I could construct another instance (rt2
) holding the following tree:
5
/ \
4 9
However, it is clear that these two trees are isomorphic (i.e. they have the same structure, and are the same up to renaming of nodes). I already have a routine computing whether two rooted trees are isomorphic (so this subproblem is already solved).
Now my question: For my purpose, I'd like a design pattern that prevents the program from actually constructing a new instance for rt2
, but instead just giving the reference to the element rt1
(which is already constructed).
On the other hand, consider another tree (rt3
), namely the following:
1
/ \
2 5
/
7
The construction routine called for this graph should create a new instance representing this graph (since this is not isomorphic to rt1
, and - thus - has not been generated up to now).
Is there such a thing?
I looked at the factory pattern, but I'm not sure (factory seems to always construct a new element). Can anybode tell me kind of "best-practice" way of solving this particular problem.