Design MVC – Factory Pattern to Prevent Multiple Instances of the Same Object

designfactory-methodmvc

I have a number of objects storing state. There are essentially two types of fields. The ones that uniquely define what the object is (what node, what edge etc), and the others that store state describing how these things are connected (this node is connected to these edges, this edge is part of these paths) etc. My model is updating the state variables using package methods, so all these objects act as immutable to anyone not in Model scope. All Objects extend one base type.

I've toyed with the idea of a Factory approach which accepts a Builder object and constructs the applicable object. However, if an instance of the object already exists (ie would return true if I created the object defined by the builder and passed it to the equal method for the existing instance) the factory returns the current object instead of creating a new instance. Because the Equal method would only compare what uniquely defines the type of object (this is node A to node B) but won't check the dynamic state stuff (node A is currently connected to nodes C and E) this would be a way of ensuring anyone that wants my Node A automatically knows its state connections. More importantly it would prevent aliasing nightmares of someone trying to pass an instance of node A with different state then the node A in my model has.

I've never heard of this pattern before, and it's a bit odd. I would have to do some overriding of serialization methods to make it work (ensure that when I read in a serilized object I add it to my facotry list of known instances, and/or return an existing factory in its place), as well as using a weakHashMap as if it was a weakHashSet to know whether an instance exists without worrying about a quasi-memory leak occuring. I don't know if this is too confusing or prone to its own obscure bugs.

One thing I know is that plugins interface with lowest level hardware. The plugins have to be able to return state that is different than my memory; to tell my memory when its own state is inconsistent. I believe this is possible despite their fetching objects that exist in my memory; we allow building of objects without checking their consistency with the model until the addToModel is called anyways; and the existing plugins design was written before all this extra state existed and worked fine without ever being aware of it.

Should I just be using some other design to avoid this crazyness? (I have another question to that affect that I'm posting).

Best Answer

The pattern you are conceptualizing is called memoization, and is much more common in functional programming but is also used heavily in games programming.

As long as you encapsulate your implementation, and don't have special cases that will drive other programmers crazy, you should be in the clear.

http://en.wikipedia.org/wiki/Memoization

Related Topic