Warning about the Singleton Pattern

Being a lover of design patterns and architectural principles, the Singleton pattern was well known by me. But my experience with this pattern was superficial at most, with components under low pressure and concurrency. Further, I recognize, under the worst production scenario, that my implementations were not thread-safe as I believed. (Good examples and solutions are in: http://www.yoda.arachsys.com/csharp/singleton.html.) Once the code was thread-safe, I bump with concurrency problems when great number of sessions where requesting the sole instance of the singleton object. Then why use Singletons in the first place?

Review the pattern: a Singleton is a class that only is instantiated once in an application, serving all clients and preserving only applications-scope static values/state. The Singleton has a method usually named GetInstance() or similar, which check the existence of the object an returns it if available or create a new instance if not. One common use of Singletons is for concrete Factory implementations. Factories are normally root objects and must persist during all time a program runs. But which benefits can we obtain with this limitations or constraint of only one instance? The real point for a Singleton is to avoid the proliferation of classes when a single set (not contradictory) of state/values are needed. In Robert C. Martin (http://www.objectmentor.com/resources/articles/SingletonAndMonostate.pdf), we could read about the effectiveness of a similar, but not singular instantiated, pattern: the Monostate. A Monostate, I believe, is a better solution, when there’s no constraint to only one instance, but a single set of values.

The Monostate pattern uses multiple class instances that conserve a single state. Thus, no matter how many instances you create, its values are the same, and any change you made in one instance, affect all other instances. But the Monostate is thread-safe and also support high concurrency, serving clients with as many instances as necessary without locking or blocking notable issues. Think for your next project, or current project with concurrency problems, give a try to monostates.

Anuncios

Responder

Por favor, inicia sesión con uno de estos métodos para publicar tu comentario:

Logo de WordPress.com

Estás comentando usando tu cuenta de WordPress.com. Cerrar sesión /  Cambiar )

Google+ photo

Estás comentando usando tu cuenta de Google+. Cerrar sesión /  Cambiar )

Imagen de Twitter

Estás comentando usando tu cuenta de Twitter. Cerrar sesión /  Cambiar )

Foto de Facebook

Estás comentando usando tu cuenta de Facebook. Cerrar sesión /  Cambiar )

w

Conectando a %s