首页 > 编程语言 > 详细

c++设计模式中的懒汉模式和饿汉模式

时间:2021-07-02 01:10:41      阅读:18      评论:0      收藏:0      [点我收藏+]

懒汉模式实现方式有两种

  • 静态指针 + 用到时初始化

  • 局部静态变量

为什么叫做懒汉模式,就是不到调用getInstance函数,这个类的对象是一直不存在的

懒汉模式的指针写法

#include <iostream>

using namespace std;
class A{
public:
    void setUp(){
        cout<<"inside setup"<<endl;
    }
    A(){
        cout<<"constructor called!"<<endl;
    }
    static A* getInstance();
    static A* aa;
};
A* A::aa = nullptr;
A* A::getInstance(){
    if(aa == nullptr)
        aa = new A;
    return aa;
}

int main(){                                                                                              
    A* aa1 = A::getInstance();
    A* aa2 = A::getInstance();

    if(aa1 == aa2)
        cout << "Yes" <<endl;
    else
        cout << "No" <<endl;
    cout << "Hello world!"<<endl;
    return 0;
} 

懒汉模式的局部变量

#include <iostream>
  using namespace std;
  
  class A{
  public:
      static A& getInstance();
      void setup(){
          cout<<"inside setup"<<endl;
      }   
  private:
      A(){
          cout<<"constructor called!"<<endl;
      }   
  };
  
  A& A::getInstance(){
      static A a;
      return a;
  }
  
  int main()
  {
     A a1 = A::getInstance();
     A a2 = A::getInstance();
  
      cout<<"Hello world!"<<endl;
      return 0;                                                                                          
  }

饿汉模式实现方式有两种

  • 饿了肯定要饥不择食。所以在单例类定义的时候就进行实例化。故没有多线程的问题。

  • 直接定义静态对象

  • 静态指针 + 类外初始化时new空间实现

局部静态变量写法

  #include <iostream>                                                                                    
  
  using namespace std;
  class A{
  public:
      static A &getInstance(){
          return aa; 
      }   
      void setup(){
          cout<<"inside setup!"<<endl;
      }   
  private:
      A(){
          cout<<"constructor called!"<<endl;
      }   
      static A aa; 
  };
  A A::aa;
  
  int main(){
    A aa1 = A::getInstance();
    A aa2 = A::getInstance();
     cout << "Hello world!"<<endl;
     return 0;
  }

静态指针写法

#include <iostream>
using namespace std;

class A{
public:
    static A* getInstance(){
        return aa;
    }
    void setup(){
        cout<<"inside setup!"<<endl;
    }
private:
    static A* aa;
    A(){
        cout<<"constructor called!"<<endl;
    }
};
A* A::aa = new A;                                                                                        

int main()
{
    A* aa1 = A::getInstance();
    A* aa2 = A::getInstance();

    if(aa1 == aa2)
        cout<<"Yes"<<endl;
    else
        cout<<"No"<<endl;
    cout << "Hello world!"<<endl;
    return 0;
}

c++设计模式中的懒汉模式和饿汉模式

原文:https://www.cnblogs.com/lodger47/p/14959807.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!