Implementation of Single instance design pattern

Source: Internet
Author: User
Tags class definition constructor terminates

Single instance design is probably the most widely used design pattern. The idea is to ensure that a class has only one instance and provides full access to the class object. Single-instance objects are used in a wide range of applications: such as GUI application must be a single mouse, modem connection needs one and only a telephone line, the operating system can only have a window manager, a PC with a keyboard. This article will discuss how to implement a single instance pattern in C + + and explain how to optimize the design of single-threaded applications.

Design scheme

Using the full object ensures easy access to the instance, but it is not guaranteed to declare only one object-that is, a local instance of the same class can still be created, except for a full instance. Single instance mode manages its unique instance through the class itself, which provides a solution to the problem. A unique instance is a normal object of a class, but when you design this class, it can only create an instance and provide full access to the instance. The unique instance class singleton hides the operation of creating an instance in a static member function. It is customary to call this member function instance (), whose return value is a pointer to a unique instance. The definition of Singleton is as follows:

class Singleton
{
public:
static Singleton* Instance();
protected:
Singleton();
Singleton(const Singleton&);
Singleton& operator= (const Singleton&);
private:
static Singleton* pinstance;
};

You can also create classes that have names such as Mouse,filemanager,scheduler and declare the corresponding members. To ensure that a user cannot create a local instance of a class, the Singleton constructor is an assignment operator, and a copy of the constructor is declared as protected. A private static instance pointer is also declared in the class. When a static function instance () is invoked for the first time, it creates a unique instance, assigns the instance address to Pinstance, and returns the address. In each concurrent invocation, Instance () will return only this address.

The following is the implementation of the class:

Singleton* Singleton::pinstance = 0;// 初始化指针
Singleton* Singleton::Instance ()
{
if (pinstance == 0) // 是第一次调用吗?
{
pinstance = new Singleton; // 创建唯一实例
}
return pinstance; // 唯一实例的地址
}
Singleton::Singleton()
{
//... 实现必要的实例初始化
}

The only way for a user to access a unique instance is instance () member functions. If you do not pass this function, any attempt to create the instance will fail because the constructor of the class is protected. Instance () is initialized with laziness, which means that the value it returns is created when the function is first accessed. This is a bulletproof design-all calls after instance () return a pointer to the same instance:

Singleton *p1 = Singleton::Instance();
Singleton *p2 = p1->Instance();
Singleton & ref = * Singleton::Instance();

Although the example in this article is for a single instance, the design template can be applied to a variable number of instance situations with a slight modification to instance (). A class allows up to five instances.

Optimize the Singleton class to fit the single threaded application

Singleton uses operator new to allocate storage space for unique instances. Because the new operator is thread-safe, you can use this design template in multithreaded applications. But there is a flaw: it is necessary to destroy the instance manually with the delete before the application terminates. Otherwise, not only does it cause a memory overflow, but it also causes unpredictable behavior because the singleton destructor will not be invoked at all. Single-threaded applications can easily avoid this problem by replacing dynamic instances with local static instances. The following is a slightly different implementation from the above instance (), which is specifically designed for single threaded applications:

Singleton* Singleton::Instance ()
{
static Singleton inst;
return &inst;
}

The local static object instance Inst is constructed the first time the instance () is invoked and remains active until the application terminates. The pointer pinstance becomes redundant and can be removed from the class definition. Unlike dynamically allocated objects, static objects are automatically destroyed when the application terminates, so there is no need to manually destroy the instance.

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.