There are several ways to implement the singleton pattern in C #. I present here, in turn order of elegance, with the most common initiative, which is not thread-safe, and work up to a full high lazily, thread-safe, simple and highly performant version. Note that the code here, do not use the personal älterer because it is the default for class members. In many other languages like Java, there is a different ruling, private and should be used.
The Singleton pattern is of two known models of software engineering. Essentially, a singleton is a class that only allows a single instance of itself to be made, and usually gives simple access to that instance. More commonly, not only can specify parameters to generate the instance - as the application otherwise the second one case, but with a parameter might be problematic! (If the same instance should have access to all applications with the same parameter, the factory pattern is more appropriate.) This article is concerned only with the situation in which no parameters are required. Usually, one requirement is that children are created only lazy - ie that the instance is not created until needed first.
- A single constructor, which is private and no parameters. This prevents other classes of instances (which would be a violation of the guideline). Note that also prevents subclassing - if a product can be a subclass only once can be a subclass twice, and if each of these subclasses can create an instance, the pattern is violated. The factory pattern can be used if you need a single example of a base type, but the exact type is not known until runtime.
- The class is sealed. This is unnecessary, strictly speaking, by the previous point, but can help to optimize the JIT things.
- A variable that contains a reference to the single created instance, if any.
- A means of obtaining public static reference to the single created instance, creating one if necessary.
0 comments:
Post a Comment