1

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.

4

3 回答 3

1

您可以使用享元模式。

1

在 flyweights 数组中,您保存所有树,其中树的类型为ITree( Flyweight)。ConcreteFlyweight可以称为BinaryTree或,作为你的名字RT。您必须在树实现中实现相等的操作才能在GetFlyweight方法中使用。

于 2013-04-21T18:15:21.950 回答
0

通常,当您想要一个对象的一个​​实例并想要返回该单个实例时,您会使用 Singleton。不完全确定您是如何将其与创建树联系起来的,但它可能是 Singelton 和 Factory 的混合体。您谈论的所有模式都是创建类型模式:http ://en.wikipedia.org/wiki/Creational_pattern

这里是单例的描述:http ://en.wikipedia.org/wiki/Singleton_pattern

于 2013-04-21T12:59:36.263 回答
0

在我看来,您希望构建一个原型实例。在这种情况下,您需要使用原型设计模式。

见: http: //www.dofactory.com/Patterns/PatternPrototype.aspx

于 2013-04-21T13:00:03.330 回答