C++版本:

class Singleton
{
public:
    static Singleton& getInstance()
    {
        return instance;
    }
private:
    Singleton(){};
    Singleton(const Singleton&);
    Singleton& operator=(const Singleton&);

    static Singleton instance;
};
Singleton Singleton::instance;

注意:

1.getInstance返回的是引用,如果不是引用则调用了一次拷贝构造,产生临时对象。

2.拷贝构造和赋值运算符要私有化,否则有可能产生新的对象。

如不对拷贝构造私有化执行下面语句

Singleton s1 = Singleton::getInstance();

这里调用拷贝构造产生了新的对象s1,虽然s1是对static instance的浅拷贝,但这不符合单例的特征。

3.注意对static instance的定义性说明。

 

java版本:

class Singleton {
   
    private Singleton() {};
    private static Singleton instance = new Singleton();
   
    public static Singleton createInstance() {
        return instance;
    }
}

相关文章:

  • 2022-12-23
  • 2021-06-16
  • 2022-12-23
  • 2021-12-31
  • 2022-12-23
  • 2022-12-23
  • 2021-10-28
猜你喜欢
  • 2021-06-22
  • 2021-09-26
  • 2022-12-23
  • 2021-11-30
  • 2022-12-23
  • 2021-09-21
  • 2021-04-26
相关资源
相似解决方案