Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What situations does a Monostate pattern model?

I know what both a Singleton or a Monostate are and how to implement them. Although I can see many uses for a Singleton, I can't imagine a situation where I would want to let the user create as many instances of my class although in reality only one really exists behind the scenes.

Can anybody help me here? I know that for several reasons one should stay away from both patterns, but in theory, what kind of problems does the Monostate model?

Thanks

like image 299
devoured elysium Avatar asked Apr 05 '10 03:04

devoured elysium


1 Answers

Monostate, to my eyes, is not a pattern you're likely to implement at an application level, but can be useful at an infrastructure level. This comment on Alex Martelli's presentation of the pattern in Python provides an illustrative example.

Consider a DCOM or .NET remoting scenario, where we have an object on the server representing a Person named Bob. Bob is not a singleton, because Bob is not the only Person. But several clients may be talking to Bob at the same time. In each case, the client does not have a direct reference to Bob (who is in a different address space or on a different machine), but instead has a proxy object. And that proxy object is local to that particular client.

So we have multiple proxy objects, each with different identity, but each proxying the state and behaviour of Bob the server object -- and therefore sharing state and behaviour. If client Alice updates Bob's state (by calling a method on her proxy object), then client Carol will see changes in Bob's behaviour (when she calls methods on her proxy object). Alice and Carol's proxy objects do not have the same object identity, but do have the same state and behaviour: both represent Bob. The two proxies exhibit the Monostate pattern.

(The whole thread is worth reading for a more detailed discussion, but the above for me was where it clicked into focus.)

like image 69
itowlson Avatar answered Oct 10 '22 12:10

itowlson