Design Patterns

All materials on our website are shared by users. If you have any questions about copyright issues, please report us to resolve them. We are always happy to assist you.
of 24

Please download to get full document.

View again

Exploring the Singleton Design Pattern Introduction In the course of developing software applications, repetitive patterns emerge as the application is developed. As whole software systems are developed, many of these same patterns become evident at scale. This concept of repetitive pattern is evident in other applications. One such application is automobile manufacturing. Many different automobile models share the same sub-assemblies from the most basic components, such as light bulbs and faste
  Exploring the Singleton Design Pattern Introduction In the course of developing software applications, repetitive patterns emerge as the application is developed. As wholesoftware systems are developed, many of these same patterns become evident at scale.This concept of repetitive pattern is evident in other applications. One such application is automobile manufacturing. Manydifferent automobile models share the same sub-assemblies from the most basic components, such as light bulbs andfasteners, to larger assemblies, such as chassis and engines.In homebuilding, the repetitive pattern concept applies to screws and nails as well as to whole building electrical distributionsystems. Whether a team is assembled to create a new automobile or a new building design, it usually does not have toponder problems that were solved before. If a team assigned to design and build a house had to rethink and design everysingle component of the house, the whole process would take much longer than it currently does. Design decisions such asthe height of a door or the function of a light switch are well understood. A house designer does not have to redesign andreconstruct a different type of device to deliver and collect water in order to meet a requirement to supply hand washingfunctionality to different parts of the house: a standard sink, as well as a standard interface of hot and cold water inputs anddrain water output, are well understood components of house construction. The repetitive pattern concept can be appliedover and over to nearly everything we surround ourselves with, including software.The automobile and homebuilding examples help visualize some general abstract concepts in software design andconstruction. The concept of well-defined general purpose units of functionality that are well understood is the motivation fordesign patterns and the focus of two other design pattern articles,Exploring the Factory Design PatternandExploring the Observer Design Pattern. These patterns cover nearly every aspect of object-oriented software design including objectcreation, object interaction, and object lifetime. For the scope of this article, we are going to discuss the Singleton pattern,which lives in a family of creational patterns.Creational patterns dictate how and when objects get created. Many instances require special behavior that can only besolved though creational techniques, rather than trying to force a desired behavior after an instance is created. One of thebest examples of this type of behavioral requirement is contained in the Singleton pattern. The Singleton pattern wasformally defined in the classic reference, Design Patterns: Elements of Reusable Software by Erich Gamma, Richard Helm,Ralph Johnson, and John Vlissides (also known as the Gang of Four, or GoF). This pattern is one of the least complicated, aswell as most popular, in Design Patterns . However, as we will see, there can be problems with implementing this pattern.This article attempts to examine the Singleton pattern from its beginning though various early implementations, as well ashow to best use it in Microsoft® .NET application development. Singleton Pattern The intent of the Singleton pattern as defined in Design Patterns is to ensure a class has only one instance, and provide aglobal point of access to it .What problem does this solve, or put another way, what is our motivation to use it? In nearly every application, there is aneed to have an area from which to globally access and maintain some type of data. There are also cases in object-oriented(OO) systems where there should be only one class, or a predefined number of instances of a class, running at any giventime. For example, when a class is being used to maintain an incremental counter, the simple counter class needs to keeptrack of an integer value that is being used in multiple areas of an application. The class needs to be able to increment thiscounter as well as return the current value. For this situation, the desired class behavior would be to have exactly oneinstance of a class that maintains the integer and nothing more.  At first glance, one might be tempted to create an instance of a counter class as a just a static global variable. This is acommon technique but really only solves part of the problem; it solves the problem of global accessibility, but does nothingto ensure that there is only one instance of the class running at any given time. The responsibility of having only oneinstance of the class should fall on the class itself and not on the user of the class. The users of the class should always befree from having to monitor and control the number of running instances of the class.What is needed is a way to control how class instances are created and then ensure that only one gets created at any giventime. This would give us exactly the behavior we require and free a client from having to know any class details. Logical Model The model for a singleton is very straightforward. There is (usually) only one singleton instance. Clients access the singletoninstance through one well-known access point. The client in this case is an object that needs access to a sole instance of asingleton. Figure 1 shows this relationship graphically. Figure 1. Singleton pattern logical model Physical Model The physical model for the Singleton pattern is also very simple. However, there are several slightly different ways thatsingletons have been implemented over time. Let's look at the srcinal GoF singleton implementation. Figure 2 shows a UMLmodel of the srcinal Singleton pattern as defined in Design Patterns . Figure 2. Singleton pattern physical model from design patterns What we see is a simple class diagram showing that there is a private static property of a singleton object as well as publicmethod Instance() that returns this same property. This is really the core of what makes a singleton. The other propertiesand methods are there to show additional operations that may be allowed on the class. For the purpose of this discussion,let's focus on the instance property and method.Clients access any instance of a singleton only through the Instance method. How the instance gets created is not definedhere. What we also want to be able to do is control how and when an instance will get created. In OO development, specialobject creation behavior is generally best handled in the constructor for a class. This case is no different. What we can do isdefine when and how we construct a class instance and then keep any client from calling the constructor directly. This is theapproach always used for singleton construction. Let's look at the srcinal example from Design Patterns . The C++ SingletonSample Implementation Code example shown below is generally considered the default implementation for a singleton. Thissample has been ported to many other programming languages and generally exists everywhere in very near this sameform. C++ Singleton Sample Implementation Code   // Declarationclass Singleton {public:static Singleton* Instance();protected:Singleton();private:static Singleton* _instance;} // ImplementationSingleton* Singleton::_instance = 0;Singleton* Singleton::Instance() {if (_instance == 0) {_instance = new Singleton;}return _instance;}Let’s examine this code for a moment. This simple class has one member variable and that is a pointer to itself. Notice thatthe constructor is protected and that the only public method is the Instance method. In the implementation of the Instancemethod, there is a control block (if) that checks to see if the member variable has been initialized, and if not creates a newinstance. This lazy initialization in the control block means that the Singleton instance is initialized, or created, only on thefirst call to the Instance() method. For many applications, this approach works just fine. But, for multithreaded applications,this approach proves to have a potentially hazardous side effect. If two threads manage to enter the control block at thesame time, two instances of the member variable could be created. To solve this, you might be tempted to merely place acritical section around the control block in order to guarantee thread safety. If you do this, then all calls to the Instancemethod would be serialized and could have a very negative impact on performance, depending on the application. It is forthis reason that another version of this pattern was created that uses something called a double-check mechanism. The nextcode sample shows an example of a double-check lock using Java syntax. Double-Check Lock Singleton Code Using Java Syntax  // C++ port to Javaclass Singleton{public static Singleton Instance() {  if (_instance == null) {synchronized (Class.forName( Singleton )) {if (_instance == null) {_instance = new Singleton();}}}return _instance;}protected Singleton() {}private static Singleton _instance = null;}In the Double-Check Lock Singleton Code Using Java Syntax sample, we perform a direct port of the C++ code to Java codein order to take advantage of the Java critical section block (synchronized). The major differences are that there are nolonger separate declaration and implementation sections, there are no pointer data types, and a new double-checkmechanism is in place. The double check occurs at the first IF block. If the member variable is null, then the execution entersa critical section block where the member variable is double checked again. Only after passing this last test is the membervariable instantiated. The general thinking is that there is no way that two threads can create two instances of the classusing this technique. Also, since there is no thread blocking at the first check, most calls to this method would not get theperformance hit of having to enter the lock. Currently, this technique is widely used in many Java applications whenimplementing a Singleton pattern. This technique is subtle but flawed. Some optimizing compilers can optimize out or reorderthe lazy initialization code and reintroduce the thread safety problem. For a more in-depth explanation, see The Double-Check Locking is Broken Declaration.Another way to attempt to fix this problem could be using the volatile keyword on the member variable declaration. Thisshould tell the compiler to not reorder the code and forgo optimization. Currently this is only a proposed memory model for aJVM and does not solve the problem right now.What is the best way to implement a singleton? It turns out, and not by accident, that the Microsoft .NET Framework hasaddressed all of these issues, thus making it easier to implement a singleton without the adverse side effects we discussedthus far. The .NET Framework, along with the C# language, allows us to port the preceding Java syntax to C# syntax bysubstituting language keywords where appropriate. So the singleton code becomes the following: Double-Check Lock in C#  // Port to C#class Singleton{public static Singleton Instance() {if (_instance == null) {lock (typeof(Singleton)) {
Related Search
We Need Your Support
Thank you for visiting our website and your interest in our free products and services. We are nonprofit website to share and download documents. To the running of this website, we need your help to support us.

Thanks to everyone for your continued support.

No, Thanks
Jurassic World Evolution: Deluxe Edition [RePack] [RUS + ENG + 9 / RUS + ENG] (2018) ( + 2 DLC) | Thám Tử Lừng Danh Conan chap 1003 | Apple Iphone 7 - 128gb - Silber (ohne Simlock) A1778 (gsm)