Patterns: Local Singleton vs. Global Singleton? - c#

There is a pattern that I use from time to time, but I'm not quite sure what it is called. I was hoping that the SO community could help me out.
The pattern is pretty simple, and consists of two parts:
A factory method that creates objects based on the arguments passed in.
Objects created by the factory.
So far this is just a standard "factory" pattern.
The issue that I'm asking about, however, is that the parent in this case maintains a set of references to every child object that it ever creates, held within a dictionary. These references can sometimes be strong references and sometimes weak references, but it can always reference any object that it has ever created.
When receiving a request for a "new" object, the parent first searches the dictionary to see if an object with the required arguments already exists. If it does, it returns that object, if not, it returns a new object and also stores a reference to the new object within the dictionary.
This pattern prevents having duplicative objects representing the same underlying "thing". This is useful where the created objects are relatively expensive. It can also be useful where these objects perform event handling or messaging - having one object per item being represented can prevent multiple messages/events for a single underlying source.
There are probably other reasons to use this pattern, but this is where I've found this useful.
My question is: what to call this?
In a sense, each object is a singleton, at least with respect to the data it contains. Each is unique. But there are multiple instances of this class, however, so it's not at all a true singleton.
In my own personal terminology, I tend to call the parent class a "global singleton". I then call the created objects "local singletons". I sometimes also say that the created objects have "reference equality", meaning that if two variables reference the same data (the same underlying item) then the reference they each hold must be to the same exact object, hence "reference equality".
But these are my own invented terms, and I am not sure that they are good ones.
Is there standard terminology for this concept? And if not, could some naming suggestions be made?
Thanks in advance...
Update #1:
In Mark Seemans' reply, below, he gives the opinion that "The structure you describe is essentially a DI Container used as a Static Service Locator (which I consider an anti-pattern)."
While I agree that there are some similarities, and Mark's article is truly excellent, I think that this Dependency Injection Container / Static Service Locator pattern is actually a narrower implementation of the general pattern that I am describing.
In the pattern described in the article, the service (the 'Locator' class) is static, and therefore requires injection to have variability in its functionality. In the pattern I am describing, the service class need not be static at all. One could provide a static wrapper, if one wants, but being a static class is not at all required, and without a static class, dependency injection is not needed (and, in my case, not used).
In my case the 'Service' is either an interface or an abstract class, but I don't think that 'Service' and 'Client' classes are even required to be defined for the pattern I am describing. It is convenient to do so, but if all the code is internal, the Server class could simply be a 'Parent' class that controls the creation of all children via a factory method and keeps weak (or possibly strong) references to all of its children. No injection, nothing static, and not even a requirement to have defined interfaces or abstract classes.
So my pattern is really not a 'Static Service Locator' and neither is it a 'Dependency Injection Container'.
I think the pattern I'm describing is much more broad than that. So the question remains: can anyone identify the name for this approach? If not, then any ideas for what to call this are welcome!
Update #2:
Ok, it looks like Gabriel Ščerbák got it with the GoF "Flyweight" design pattern. Here are some articles on it:
Flyweight pattern (Wikipedia)
Flyweight design pattern (dofactory.com)
Flyweight Design Pattern (sourcemaking.com)
A 'flyweight factory' (server) and 'flyweight objects' (client) approach using interfaces or abstract classes is well explained in the dofactory.com article an is exactly what I was trying to explain here.
The Java example given in the Wikipedia article is the approach I take when implementing this approach internally.
The Flyweight pattern also seems to be very similar to the concept of hash consing and the Multiton pattern.
Slightly more distantly related would be an object pool, which differs in that it would tend to pre-create and/or hold on to created objects even beyond their usage to avoid the creation & setup time.
Thanks all very much, and thanks especially to Gabriel.
However, if anyone has any thoughts on what to call these child objects, I'm open to suggestions. "Internally-Mapped children"? "Recyclable objects"? All suggestions are welcome!
Update #3:
This is in reply to TrueWill, who wrote:
The reason this is an anti-pattern is because you are not using DI. Any class that consumes the Singleton factory (aka service locator) is tightly coupled to the factory's implementation. As with the new keyword, the consumer class's dependencies on the services provided by the factory are not explicit (cannot be determined from the public interface). The pain comes in when you try to unit test consumer classes in isolation and need to mock/fake/stub service implementations. Another pain point is if you need multiple caches (say one per session or thread)
Ok, so Mark, below, said that I was using DI/IoC. Mark called this an anti-pattern.
TrueWill agreed with Mark's assessment that I was using DI/IoC in his comment within Mark's reply: "A big +1. I was thinking the same thing - the OP rolled his own DI/IoC Container."
But in his comment here, TrueWill states that I am not using DI and it is for this reason that it is an anti-pattern.
This would seem to mean that this is an anti-pattern whether using DI or not...
I think there is some confusion going on, for which I should apologize. For starters, my question begins by talking about using a singleton. This alone is an anti-pattern. This succeeded in confusing the issue with respect to the pattern I am trying to achieve by implying a false requirement. A singleton parent is not required, so I apologize for that implication.
See my "Update #1" section, above, for a clarification. See also the "Update #2" section discussing the Flyweight pattern that represents the pattern that I was trying to describe.
Now, the Flyweight pattern might be an anti-pattern. I don't think that it is, but that could be discussed. But, Mark and TrueWill, I promise you that in no way am I using DI/IoC, honest, nor was I trying to imply that DI/IoC is a requirement for this pattern.
Really sorry for any confusion.

It looks like classic Flyweight design pattern from the GoF book. It does not cover the singleton factory with hash map, but generally covers saving on space and performance by reusing already created object, which is referenced by many other objects. Check out this pattern.

The objects themselves aren't following the singleton pattern, so maybe referring to the fetched objects as singleton can be confusing.
What about a Recycling Factory? :]

The structure you describe is essentially a DI Container used as a Static Service Locator (which I consider an anti-pattern).
Each of the services created by this Service Locator has a so-called Singleton lifetime. Most DI Containers support this as among several available lifetimes.

Related

Why Parameterless factory methods are Leaky Abstraction? [closed]

Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 1 year ago.
Improve this question
I'm reading a book which says:
// code smell
public interface IProductRepositoryFactory {
IProductRepository Create();
}
The Dependencies created by an Abstract Factory should conceptually require a runtime value, and the translation from a runtime value into an Abstraction should make sense.
By specifying an IProductRepositoryFactory Abstraction with a parameterless
Create method, you let the consumer know that there are more instances of the given
service, and that it has to deal with this. Because another implementation of IProductRepository might not require multiple instances or deterministic disposal at all,
you’re therefore leaking implementation details through the Abstract Factory with its
parameterless Create method.
I'm a little bit confused here, what does "more instances of the given service" mean, does it mean that you call a concrete Factory's Create method multiple times? what's wrong with that? even if you have factory methods that does have parameters as:
public interface IProductRepositoryFactory {
IProductRepository Create(string type);
}
and if you call a concrete Factory's Create method multiple times there will be multiple instances too. so what's wrong with parameterless factory methods? what does it leak?
An abstraction is "leaky" when it fails to hide details of the underlying implementation that it is supposed to hide.
It isn't true that a parameterless factory method is always leaky, because that of course depends on what the abstraction it returns is supposed to hide, and the author you reference never really specifies what information details are exposed that are supposed to remain hidden.
But what he says is often correct. If you provide this IProductRepositoryFactory method, then the receiver can create as many instances of IProductRepository as it likes... but why would the receiver want to make one, or two, or a bunch? If you pass this factory interface, then the choice is probably important. The receiver must know about the kinds of trade-offs involved in making one instance vs. many. It probably has to do with caching, thread pooling, etc.
Often, this is the kind of implementation detail that the receiver should not have to know about.
But, you know...
It is actually pretty common and perfectly fine under many circumstances to inject interfaces that look a lot like this case, and this gets into fussing about the definitions of words.
For instance, you might pass in a factory that the receiver would use like this:
factory.createDocument().setTitle(title).setContent(content).save();
Perfectly fine. What's the difference? Well, in this case it's that the document we're creating is not a "Dependency". The factory itself is the dependency. The service it provides is the ability to create documents, which the caller will then own. These documents are obviously stateful and have identity. This is not something that the Document abstraction is supposed to hide at all, and so this is not a leaky abstraction.
Similar patterns happen a lot when working with multithreaded code. You will quite often have a thread-safe factory service that creates objects that are not thread-safe.
does it mean that you call a concrete Factory's Create method multiple times? what's wrong with that?
Well, their point is that you don't know what to do with the product repository. Is it a singleton? Then it should be an actual singleton instance, not coming from a factory. Is it disposable? Well, you're returning a IProductRepository, not an IDisposable, so there's nothing to suggest that you should be disposing that.
even if you have factory methods that does have parameters [...] if you call a concrete Factory's Create method multiple times there will be multiple instances too
I believe their thinking is that you'd be getting already built instances based on your parameters that are cached between runs, so there's no disposing involved.
I'm not sure I fully agree with their thinking, but I will say that in my opinion you'll never sell this pattern to me. Either use a singleton, or dependency injection (which supersedes singletons as well).
To address this question properly really requires reading the full article for any readers of the answers here to have the necessary context. In terms of the specifics of your particular question, here's some clarification on the concerns that are raised:
Injecting the factory instead of the service itself puts the onus of lifetime management of the dependency (IProductRepository) on the consumer (HomeController). If the dependency was injected instead of the factory, a proxy class or the IoC framework could be charged with lifetime management, freeing up the consumer to focus on working with the API surface of the dependency.
Use of a proxy repository class could further limit the leak, as IDisposable would no longer be implemented by IProductRepository nor exposed to the consumer since the proxy would manage lifetime.
The Create method of the factory implies that multiple instances of whatever implementation is being handed back can be created. Again, this places extra and unnecessary responsibility on the consumer to manage- or at least be concerned with this when it could be handled elsewhere. As pointed out in Matt's answer there are circumstances where it's perfectly fine- if not expected- to be able to generate more than one instance from a factory. In the article in question it's really a matter of the repository pattern and the conventions that come with it that makes the design awkward; typically it doesn't make sense to have multiple instances of a given type of repository but by injecting the factory instead of the factory instance, the code allows this thus creating the leak.
Overall, most of the concern here revolves around the fact that a factory is being injected as a dependency instead of the dependency itself which ultimately requires more knowledge of the dependency than is necessary on the consumer end. The parameterless factory method returning an abstraction further compounds this. If some runtime information needed to be provided in order for that factory to make a decision as to what concrete type to instantiate and hand back as an abstraction, injecting the factory would make more sense. As it stands it's just not great design, and poor design can lead to additional mental overhead. The fact that the Create method hands back an interface instance instead of a concrete instance without accepting any parameters might a) raise questions as to why the factory would hand back an instance of one type or another, thus requiring knowledge of how the factory makes its decisions, or b) require knowledge of the fact that there is only one implementation of IProductRepository. Neither of these are anything that the consumer, or the developers leveraging the dependency, should really have to concern themselves with. A proper abstraction combined with proper IoC mitigates these concerns.

Autofac: register component as different services using different constructors

I would like to register a singleton component for multiple services and define which constructor to use, depending on which service was used during the resolve call.
I tried this:
_builder.RegisterType<TComponent>()
.As<IService1>()
.FindConstructorsWith(ConstructorFinder1)
.SingleInstance();
_builder.RegisterType<TComponent>()
.As<IService2>()
.FindConstructorsWith(ConstructorFinder2)
.SingleInstance();
But this leads to two different "singleton" instances, depending on which service was used.
So I tried:
_builder.RegisterType<TComponent>()
.As<IService1>()
.FindConstructorsWith(ConstructorFinder1)
.As<IService2>()
.FindConstructorsWith(ConstructorFinder2)
.SingleInstance();
This solves the singleton issue, but sadly the second FindConstructorsWith call overrides the first call, i.e. for both services ConstructorFinder2 is used.
I had assumed (hoped) that the ConstructorFinders would be stored with respect to the service, but apparently this is not the case.
Is what I'm trying to achieve conceptually wrong, does Autofac not support it or am I simply missing something?
EDIT:
Once again thanks to Travis for his great response. Apparently I left out a few details that made things confusing. Let me add some now.
This question was actually a kind of follow-up to How to determine which constructor Autofac uses when resolving (where Travis also helped me along). So the issue comes up when deserializing and it affects many different objects.
I get the arguments about composition, seperation of concerns and how having several ctors is often considered a code smell, but in the context of deserialization (at least for the app I'm currently developing) it is extremely useful to be able to create instances differently, depending on if they are newly built or deserialized from a project file. Several members that need to be initialized when building a new instance do not have to be initialized when deserializing (because their values would be overridden during deserialization anyway). It would mean extra performance costs and (and, in this case) cause other issues regarding the throw-away-initializations.
After spending days trying to find a solution (with complications also coming from the Newtonsoft Json side) I've decided to discontinue Autofac and implement our own IOC container. For general purposes it cannot (obviously!) compete with Autofac in any way, but since we were really only using a small subset of Autofac's great features, I felt we could try to roll our own. It took me a lot less than the days I've spent on trying to wrap my head around a monolithic black box. Yes, Autofac is open source, but stepping through the code no walk in the park.
First tests are very promising and it feels good to regain full control of such a vital component of the application.
Again, the reason for leaving Autofac was that it is not (feasibly) possible to define how a singleton component is constructed depending on the service it was constructed for. And from a general structure/concept point-of-view I understand that it makes sense to strictly seperate the service and the construction-how-tos. But during deserializing things are different, I believe. And, now that I'm independent of Autofac, I may decide to alter the mechanisms so they fit into the overall concept in a more straight-forward way.
This is sort of a difficult question to answer because it seems you have some underlying goal you're trying to achieve and you have a solution you want to work but perhaps it's the wrong solution and you should ask a [new] question depending on how this response works out for you.
Let me walk this through to see if I can explain why it's hard to answer.
I would like to register a singleton component for multiple services and define which constructor to use, depending on which service was used during the resolve call.
If it's a singleton that means there's one in the whole system, right? It'll be effectively "first in wins." If something resolves it as an IService1 then the constructor associated with that will be called and even if you try resolving it as IService2 later no construction will happen because the singleton was created. The converse is also true - IService2 gets resolved and the constructor path is followed there, then things asking for IService1 will get the singleton and no constructor is called.
That raises a concern:
If you know which thing, for sure, will be resolving first, then why do you need two different constructor selectors?
If you don't know which thing will be resolving first, then are you accounting for the system unpredictability?
I have seen these sorts of questions before and usually what they indicate is one of two things:
You are trying to do some sort of selection or special logic based on context. There's an Autofac FAQ about this that may help. Usually the way around this is to refactor. I'll get back to that in a second.
You are trying to "share registrations" between two different applications. The answer to this is to use Autofac modules and reuse those; but if there are special registrations for each app type, let that happen.
This isn't to say that either of these are what you're asking for, but this is where I've seen such questions. Usually there's some unspoken goal where a solution has been pre-chosen and it's better ask how to solve the goal rather than how to implement a very specific solution. Again, I could be wrong.
On the refactoring note for item 1, above, I can further guess based on the desire for a singleton that there's some sort of resource like a database connection that needs to be shared or is expensive to spin up. Consider splitting the TComponent into three separate classes:
TCommonExpensiveComponent - this is the stuff that is actually expensive to spin up and really does need to be a singleton, but does not differ across IService1 and IService2.
TService1 - implement IService1 with only the required constructor so you don't need a constructor finder. Have it consume TCommonExpensiveComponent.
TService2 - implement IService2 with only the required constructor so you don't need a constructor finder. Have it consume TCommonExpensiveComponent.
The idea being avoid the complexity of registrations, keep the shared/singleton that you want, and still get different constructor usage as needed. You may want to throw in some common base/abstract class, too, that the TService classes can derive from if there's really a lot of common logic.
Is what I'm trying to achieve conceptually wrong, does Autofac not support it or am I simply missing something?
Technically you could do some really crazy stuff in Autofac if you wanted to, like write a custom registration source that waits for someone to query for the IService1 or IService2 registration and then picks a constructor based on that, dynamically serving the registration as needed. But, truly, don't even start down this road.
Instead, it would be good to clarify what the problem is that you're trying to solve and how you plan on working around the challenges listed above if my response here doesn't help. Do that in a brand new question that goes into more detail about your challenge and what you've tried. This not being a forum, having a conversation to try and weed out additional help given the current question really isn't feasible. Plus, taking a second to step back and maybe reframe the question sounds like it might help here.

Decorator pattern: enhanced design?

I'm reading and example provided in "Head first design patterns book" about decoration pattern.
I have noticed 2 things:
if you will need to remove a decorator from the stack of the wrapped decorators, you will have to iterate one by one through the component reference, which is O(n) complexity.
Conceptually I find it wrong to wrap (encapsulate) the base component in to the decorator object. It should be reversed; the component object should encapsulate the decorating objects.
I'm new to design patterns, and there is high probability that I'm wrong. Please explain to me what is specifically wrong with the way I think so I can learn.
I have created a different design, which solves the problems that I have mentioned. Maybe they add new problems; please feel free to point out the issues.
Here is the UML Diagram of the suggestion:
Basically what I did is that I have created a dictionary in the Component class which saves which decorators have been added, and made the Decorator abstract class not inherit from the component yet from Interface (so the component abstract class).
In this way, we can remove any decoration we want with O(1) complexity, and it is more logically constructed in the way that the component wraps the decorator, not the vice versa.
I understand that maybe I didn't noticed some advantage of the original Decorator pattern design. Please advice me.
Here is my code url.
Edit:
An example of when a customer will need to remove a decorator:
say for example the customer is choosing the condiments, he is adding whip, removing caramel, see each time how the total price vary, based on what the client is choosing to be added as a decorator.
if you will need to remove a decorator from the stack of the wrapped decorators, you will have to iterate one by one through the component reference, which is O(n) complexity.
It's true that removing decorators is theoretically more complex when they're wrapped. However, you need to consider what is a likely n. I'm going to guess for the decorator pattern as it was proposed, there are probably a small (max(n) == 20) iterators. Iterating over that many would not be a practical problem.
Conceptually I find it wrong to wrap (encapsulate) the base component in to the decorator object. It should be reversed; the component object should encapsulate the decorating objects.
The Decorator pattern seeks to add functionality (via concrete decorators) without having to modify the component class. In some cases, a Component can't be changed (e.g., it comes from a standard library). With the approach you propose, the Component would have to be modified to encapsulate its decorators. This is not the intention of Decorator.
In the original GoF book, the design patterns have clear definitions of the problem they solve, and the consequences (which are not all positive!) of the design pattern. In line with your complexity point (removing decorators), the authors mentioned this consequence:
Lots of little objects. A design that uses Decorator often results in systems composed of lots of little objects that all look alike. The objects differ only in the way they are interconnected, not in their class or in the value of their variables. Although these systems are easy to customize by those who understand them, they can be hard to learn and debug.
Why would you need to "remove a decorator from the stack of the warped decorators"? What does this mean? I think you're confusing two different concepts, the decorator pattern and stacks. The first is a design pattern in object-oriented programming, the latter is a data structure.
The decorator pattern exists so that new functionality can be added to a base component without the need to redefine the components that use/are dependent on it. That's why the decorator component "encapsulates" the base component, so that it can then use whatever functionalities it contains, while adding others required. If the base component encapsulated the decorator components, how would you reference a functionality present in any given one of them? Following you example, imagine I call Mocca.GetCost(). If it's not overriden nor redefined, CondimentDecorated.GetCost() will be called, which in turn, I imagine, considering what you're trying to do, will call Beverage.GetCost(). What will this method do? Iterate over the dictionary to look for which decorator method to call? This doesn't make sense, as, in calling CondimentDecorated.GetCost() you'll only be calling Beverage.GetCost() again. How will all this work if you can, as you said, "remove any decoration you want" from the decorators dictionary? What will be the behaviour then, when you call Mocca.GetCost()?
It's not that what you're trying to do isn't possible, and it's great to question why something is the way it is. But there's just a lot OOP misconceptions and violations here. Meaning, question not only how things could be made better, but also why they are done the way they are.

Should we seal Singletons? Should we try to inherit from Singletons in the first place?

Should a Singleton class be allowed to have children? Should we seal it? What are the pro's and con's?
For being able to inherit from a Singleton class, we would have to make the constructor protected instead of private. Now, that will be fine in c#, but the protected word in java gives both child-classes and package-classes access to the constructor. Which means not only classes that inherit from our Singleton can access the constructor but other classes in the same package can do it.
I'm a bit confused about all this facts. Maybe I am making a big fuss about nothing to worry about too much? Until now, I never had any necessity of trying to inherit from a Singleton, so maybe this is just an academic question!
Thanks
Yes, Singletons should be sealed. No, they should not be inherited.
The reason is that the primary (really only) behaviour of a Singleton is to create an instance of itself at some predetermined time. Since this functionality is static, it can't be overridden, so it would have to be duplicated instead. Once you start duplicating, you have multiple instances of a singleton, which doesn't really make sense.
Either that or you end up with race conditions or other conflicts as the "derived" singletons fight for control over the global instance, which not only doesn't make sense, it's dangerous.
There are some hackish workarounds to the Singleton inheritance problem, but that is what they are - hacks. The Singleton pattern is not really suitable for inheritance.
A better solution is to use an IoC Container framework to handle the "Singleton" (lifetime) aspect of the class. At that point you can use a POJO and simply inherit from it.
EDIT: Some links that may help:
List of .NET Dependency Injection Containers (IOC)
Open Source Inversion of Control Containers (Java)
Dependency Injection in .NET (book)
Mark Seemann's .NET blog - Dependency Injection category
Look for ones that handle lifetime management. You want to be able to configure the container (which acts like a generic factory) so that requests for instances of "Singleton" classes always return the same instance (at least for the same container). You generally only have one container instance at the highest level of your application.
Hmm, sounds like a question many of us got asked at school when learning about Singletons. I'd suggest reading the following links.
http://msmvps.com/blogs/jon_skeet/archive/2006/01/20/singleton-inheritance.aspx
http://msdn.microsoft.com/en-us/library/84eaw35x.aspx
Many would strongly discourage inheriting from a singleton, but real-life programming often requires exactly such an approach. I personally would say, don't inherit from a singleton as a rule of thumb, but don't lock yourself into a design which blocks off such an approach. A pragmatic development approach is always the best approach...
If you can extend from a singleton, then it means that you can have more than one instance of it. This contradicts the whole singleton idea. Just make it a "normal" class and write the code around it accordingly that you instantiate it only once and use the same instance forever. If you need it to be. Dependency injection can help a lot in this.
If you want to use inheritance in conjunction with the singleton pattern, you should put the inheritable state and behaviour into an abstract base class and define the singletons as (final) subclasses.

In what circumstances should I use a Singleton class?

Closed as exact duplicate of this question. But reopened, as the other Singleton questions are for general use and not use for DB access
I was thinking of making an internal data access class a Singleton but couldn't convince myself on the choice mainly because the class has no state except for local variables in its methods.
What is the purpose of designing such classes to be Singletons after all?
Is it warranting sequential access to the database which is not convincing since most modern databases could handle concurrency well?
Is it the ability to use a single connection repeatedly which could be taken care of through connection pooling?
Or Is it saving memory by running a single instance?
Please enlighten me on this one.
I've found that the singleton pattern is appropriate for a class that:
Has no state
Is full of basic "Service Members"
Has to tightly control its resources.
An example of this would be a data access class.
You would have methods that take in parameters, and return say, a DataReader, but you don't manipulate the state of the reader in the singleton, You just get it, and return it.
At the same time, you can take logic that could be spread among your project (for data access) and integrate it into a single class that manages its resources (database connections) properly, regardless of who is calling it.
All that said, Singleton was invented prior to the .NET concept of fully static classes, so I am on the fence on if you should go one way or or the other. In fact, that is an excellent question to ask.
From "Design Patterns: Elements Of Reusable Object-Oriented Software":
It's important for some classes to
ahve exactly one instance. Although
there can be many printers in a
system, there should only be one
printer spooler. There should only be
one file system and one window
manager. ...
Use the Singleton pattern when:
there must be exactly one instance of a class, and it must be accessible to clients from a well-known access point
the sole instance should be extensible by subclassing and clients should be able to use an extended instance without modifying their code
Generally speaking, in web development, the only things that should actually implement Singleton pattern are in the web framework itself; all the code you write in your app (generally speaking) should assume concurrency, and rely on something like a database or session state to implement global (cross-user) behaviors.
You probably wouldn't want to use a Singleton for the circumstances you describe. Having all connections to a DB go via a single instance of a DBD/DBI type class would seriously throttle your request throughput performance.
The Singleton is a useful Design Pattern for allowing only one instance of your class. The Singleton's purpose is to control object creation, limiting the number to one but allowing the flexibility to create more objects if the situation changes. Since there is only one Singleton instance, any instance fields of a Singleton will occur only once per class, just like static fields.
Source: java.sun.com
using a singleton here doesn't really give you anything, but limits flexibility
you WANT concurrency or you won't scale
worrying about connections and memory here is a premature optimization
As one example, object factories are very often good candidates to be singletons.
If a class has no state, there's no point in making it a singleton; all well-behaved languages will only create, at most, a single pointer to the vector table (or equivalent structure) for dispatching the methods.
If there is instance state that can vary among instances of the class, then a singleton pattern won't work; you need more than one instance.
It follows, then, by exhaustion, that the only cases in which Singleton should be used is when there is state that must be shared among all accessors, and only state that must be shared among all accessors.
There are several things that can lead to something like a singleton:
the Factory pattern: you construct
and return an object, using some
shared state.
Resource pools: you have a shared
table of some limited resources,
like database connections, that you
must manage among a large group of
users. (The bumpo version is where
there is one DB connection held by
a singleton.)
Concurrency control of an external
resource; a semaphore is generally
going to be a variant of singleton,
because P/V operations must
atomically modify a shared counter.
The Singleton pattern has lost a lot of its shine in recent years, mostly due to the rise of unit testing.
Singletons can make unit testing very difficult- if you can only ever create one instance, how can you write tests that require "fresh" instances of the object under test? If one test modifies that singleton in some way, any further tests against that same object aren't really starting with a clean slate.
Singletons are also problematic because they're effectively global variables. We had a threading issue a few weeks back at my office due to a Singleton global that was being modified from various threads; the developer was blinded by the use of a sanctioned "Pattern", not realizing that what he was really creating was a global variable.
Another problem is that it can be pathologically difficult to create true singletons in certain situations. In Java for example, it's possible to create multiple instances of your "singleton" if you do not properly implement the readResolve() method for Serializable classes.
Rather than creating a Singleton, consider providing a static factory method that returns an instance; this at least gives you the ability to change your mind down the road without breaking your API.
Josh Bloch has a good discussion of this in Effective Java.
You have a repository layer that you want created once, and that reference used everywhere else.
If you go with a standard singleton, there is a bad side effect. You basically kill testability. All code is tightly couple to the singleton instance. Now you cannot test any code without hitting the database (which greatly complicates unit testing).
My advice:
Find an IOC that you like and integrate it into your application (StructureMap, Unity, Spring.Net, Castle Windsor, Autofac, Ninject...pick one).
Implement an interface for you repository.
Tell the IOC to treat the repository as a singleton, and to return it when code is asking for the repository by the interface.
Learn about dependency injection.
This is a lot of work for a simple question. But you will be better off.
with c#, I would say that a singleton is rarely appropriate. Most uses for a singleton are better resolved with a static class. Being mindful of thread safety is extremely important though with anything static. For database access, you probably don't want a single connection, as mentioned above. Your best bet is to create a connection, and use the built in pooling. You can create a static method that returns a fresh connection to reduce code, if you like. However an ORM pattern/framework may be better still.
In c# 3.5 extension methods may be more appropriate than a static class.

Categories