If the factory always creates a new object

we have a hierarchical structure where each node is derived from the base class node public Node(INodeFactory nodeFactory)

factory is injected so that node can create child nodes withGet(int id)

At some point, some nodes need a reference to another node in the structure. The information required to obtain a link may change at runtime and is not necessarily available. When the node object was created. Basically, this method signature looks the same and Get(int id)

. This time, a new object should not be created, but an existing one should be returned.

Our first attempt was to pass INodeLocator

in which node to look for. First of all, we're not sure if "locator" is a good name, and if we are missing some pattern here, maybe a repository pattern (but only for searching?). Secondly, we noticed that the method signature is the same.

We considered switching the factory from create mode to search mode after creating the initial tree, but this will not work since the nodes have to be created later as well.

For the "locator" logic, we thought of looking up (iterating) through the nodes, but it might be better to keep track of them in a flat dictionary. But then the problem arises that the factory can add to the dictionary, but does not manage the lifetime. What happens when a node is removed.

How can we properly design this problem?

+3


source to share


1 answer


Differentiate these two functions by name and add both of them to your "factory" (which may deserve a different name). For example.

public interface INodeFactory
{
    // creates a new Node and returns it
    Node Create(int id);

    // retrieves an existing node
    Node Get(int id);

    // deletes a Node
    void Delete(int id);
}

      



The implementation stores some kind of dictionary inside itself, while the key is the key, and Node plus an indication, if it has already been deleted, is the value.

I prefer to keep both functions in the same class, as the newly created Node can be stored here and therefore inconsistencies can be easily avoided.

0


source







All Articles