Go: Design pattern Singleton (example is C #)

Source: Internet
Author: User
Tags constructor instance method return client
The Singleton of design pattern
--------------------------------------------------------------------------------

Introduction
Most of the colleagues who have read the classic "design" of "Gang of Four" (Erich Gamma, Richard Helm, Ralph Johnson, John vlissides) are sure to have a great admiration for this book. It has been said that "only after reading the design pattern", my level of programming has really been a qualitative leap. "

So, how can you get into the halls of design mode? The design pattern is a reusable, object-oriented software design solution that senior programmers have accumulated over the long run, in this sense, there are countless design patterns in the world, and the 23 design patterns summarized by "Gang of Four" are just 23 of them. The key is to grasp the "design pattern" of the idea, and then integrate them, flexible application to their own development process.

--------------------------------------------------------------------------------

Singleton mode
Singleton can be said to be the simplest and most practical design model in "Designing pattern". So, what is singleton?

As the name suggests, Singleton is to ensure that a class has only one instance. Singleton is primarily used for object creation, which means that if a class takes a singleton pattern, it will have and only one instance to access once the class is created. Most of the time we all need singleton mode, the most common example is that we want only one connection instance of the entire application to connect to the database, or to require only one instance of a user's data structure in an application. We can all use the singleton mode to achieve the goal.

At first glance, Singleton seems to be somewhat like a global object. In practice, however, it is not possible to replace the singleton pattern with a global object because: First, a large number of global objects can degrade the quality of the program, and some programming languages such as C # do not support global variables at all. Second, the global object approach does not prevent people from instantiating a class multiple times: In addition to the global instance of a class, developers can still create multiple local instances of a class through the constructor of the class. While the singleton mode gives the class itself the task of "guaranteed only one instance" by fundamentally controlling the creation of the class, there is no way for the developer to get multiple instances of the class. This is the fundamental difference between the global object approach and the singleton pattern.

--------------------------------------------------------------------------------

Implementation of Singleton model
The implementation of the singleton model is based on two key points:

1 constructs an instance of a class without directly using the constructor of the class, and providing another static method of public. Usually this method is named instance. Public guarantees its global visibility, and static methods ensure that unnecessary instances are not created.

2 The constructor of the class is set to private and the constructor is "hidden", and any method that attempts to create an instance using the constructor will error. This prevents developers from creating instances of the class directly by bypassing the instance method above.

The creation of the class can be fully controlled by the above two points: no matter how many places need to use this class, they are accessing the only instance of the class that is generated. The following C # code shows two ways to implement the singleton pattern, which developers can choose from.

Realization Way One: Singleton.cs

Using System;
Class Singletondemo
{private static Singletondemo Thesingleton = null;
Private Singletondemo () {}
public static Singletondemo Instance ()
{if (null = = Thesingleton)
{
Thesingleton = new Singletondemo ();
}
return Thesingleton;
}
static void Main (string[] args)
{Singletondemo S1 = singletondemo.instance ();
Singletondemo s2 = singletondemo.instance ();
if (S1. Equals (S2))
{Console.WriteLine ("The Only one instance!");
}
}
}

Another way of implementing this equivalence is: Singleton.cs:

Using System;

Class Singletondemo
{private static Singletondemo Thesingleton = new Singletondemo ();
Private Singletondemo () {}
public static Singletondemo Instance ()
{return Thesingleton;
}
static void Main (string[] args)
{Singletondemo S1 = singletondemo.instance ();
Singletondemo s2 = singletondemo.instance ();
if (S1. Equals (S2))
{Console.WriteLine ("The Only one instance!");
}
}
}

Compile execution:

CSC Singleton.cs

Get run Result:

The only one instance!

--------------------------------------------------------------------------------

. NET in the Singleton
Because the singleton model has such practical value, developers can also see its shadow everywhere in the implementation of many large systems, in addition to being able to use singleton patterns directly in program code. In the grand launch of Microsoft. NET Framework, the same can also be found singleton thought flashing light.

For example, in the important part of the. NET Framework remoting, remote objects are activated in two ways: server-side activation and client-activated. The object of server-side activation is divided into two kinds: Singleton object and SingleCall object. The Singleton object is an object that, regardless of how many client invocations the object has, it always has only one instance, from which all client requests are processed. Conversely, if a remote object is declared as SingleCall, a new object is created for each call to the client method, even if the method call comes from the same client, i.e., the object only exists during the method call duration, and the object is destroyed once the method call has finished. Obviously, the Singleton object here is the application of design pattern Singleton thought in. Net.

So, how in. NET remoting in the use of singleton? NET provides two ways to register a remote object as singleton: Call the RegisterWellKnownServiceType method directly, and specify the object type as singleton in the parameter or set the type of the remote object to singleton in the configuration file web.config. The two methods have the same effect, but the latter approach is more convenient, since changing the contents of the configuration file eliminates the need to recompile the application. The following code shows how to register a remote object type using the RegisterWellKnownServiceType method:

RemotingConfiguration.RegisterWellKnownServiceType (Type.GetType ("Remotingsamples.helloserver,object"), " SayHello ", Wellknownobjectmode.singleton);

The parameter "SayHello" is the URI that the client uses to represent the remote object when accessing the remote object (this is HelloServer), such as Tcp://localhost:8085/sayhello (assuming a TCP channel is used).

The last argument indicates that the remote object is a singleton type. Once the remote object is registered as singleton, the remote object is created the first time the client invokes the HelloServer method, and then it remains until the client disconnects or the object timeout is destroyed. In the meantime, no matter how many clients call this remote object, all client requests will be processed by the only instance that already exists.

This is the application of singleton in. Net.

From the realization and application of singleton mode, it can be seen that the excellent design pattern always has the beauty of simplicity. They employ an "elegant" approach that allows for simple and easy reuse of successful design methods and architectures. This is why today's software development is increasingly emphasizing "design patterns". If you want to learn more about design patterns, it's also recommended that you read Erich Gamma, Richard Helm, Ralph Johnson, John Vlissides's classic "Designing Pattern."

--------------------------------------------------------------------------------

Author: Liu Yingdan





Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.