常用十种设计模式——单例模式

十种常见设计模式及代码段总结

 1. 单例模式: 实现方式:

a) 将被实现的类的构造方法设计成private的。

 b) 添加此类引用的静态成员变量,并为其实例化。

c) 在被实现的类中提供公共的CreateInstance函数,返回实例化的此类,就是b中的静态成员变量。

应用场景: 优点:

1.在单例模式中,活动的单例只有一个实例,对单例类的所有实例化得到的都是相同的一个实例。这样就 防止其它对象对自己的实例化,确保所有的对象都访问一个实例

2.单例模式具有一定的伸缩性,类自己来控制实例化进程,类就在改变实例化进程上有相应的伸缩性。

 3.提供了对唯一实例的受控访问。

4.由于在系统内存中只存在一个对象,因此可以 节约系统资源,当 需要频繁创建和销毁的对象时单例模式无疑可以提高系统的性能。

5.允许可变数目的实例。

6.避免对共享资源的多重占用。

缺点:

1.不适用于变化的对象,如果同一类型的对象总是要在不同的用例场景发生变化,单例就会引起数据的错误,不能保存彼此的状态。

2.由于单例模式中没有抽象层,因此单例类的扩展有很大的困难。

3.单例类的职责过重,在一定程度上违背了“单一职责原则”。

4.滥用单例将带来一些负面问题,如为了节省资源将数据库连接池对象设计为的单例类,可能会导致共享连接池对象的程序过多而出现连接池溢出;如果实例化的对象长时间不被利用,系统会认为是垃圾而被回收,这将导致对象状态的丢失。 

类图:


代码示例:


/**

* The Singleton class defines the `GetInstance` method that serves as an

* alternative to constructor and lets clients access the same instance of this

* class over and over.

*/

class Singleton

{

    /**

    * The Singleton's constructor should always be private to prevent direct

    * construction calls with the `new` operator.

    */

protected:

    Singleton(const std::string value): value_(value)

    {

    }

    static Singleton* singleton_;

    std::string value_;

public:

    /**

    * Singletons should not be cloneable.

    */

    Singleton(Singleton &other) = delete;

    /**

    * Singletons should not be assignable.

    */

    void operator=(const Singleton &) = delete;

    /**

    * This is the static method that controls the access to the singleton

    * instance. On the first run, it creates a singleton object and places it

    * into the static field. On subsequent runs, it returns the client existing

    * object stored in the static field.

    */

    static Singleton *GetInstance(const std::string& value);

    /**

    * Finally, any singleton should define some business logic, which can be

    * executed on its instance.

    */

    void SomeBusinessLogic()

    {

        // ...

    }

    std::string value() const{

        return value_;

    }

};

Singleton* Singleton::singleton_= nullptr;;

/**

* Static methods should be defined outside the class.

*/

Singleton *Singleton::GetInstance(const std::string& value)

{

    /**

    * This is a safer way to create an instance. instance = new Singleton is

    * dangeruous in case two instance threads wants to access at the same time

    */

    if(singleton_==nullptr){

        singleton_ = new Singleton(value);

    }

    return singleton_;

}

void ThreadFoo(){

    // Following code emulates slow initialization.

    std::this_thread::sleep_for(std::chrono::milliseconds(1000));

    Singleton* singleton = Singleton::GetInstance("FOO");

    std::cout << singleton->value() << "\n";

}

void ThreadBar(){

    // Following code emulates slow initialization.

    std::this_thread::sleep_for(std::chrono::milliseconds(1000));

    Singleton* singleton = Singleton::GetInstance("BAR");

    std::cout << singleton->value() << "\n";

}

int main()

{

    std::cout <<"If you see the same value, then singleton was reused (yay!\n" <<

                "If you see different values, then 2 singletons were created (booo!!)\n\n" <<

                "RESULT:\n"; 

    std::thread t1(ThreadFoo);

    std::thread t2(ThreadBar);

    t1.join();

    t2.join();

    return 0;

}

©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容