Skip to content

Instantly share code, notes, and snippets.

@masaki-shimura
Last active June 15, 2021 00:26
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save masaki-shimura/748cae6af79228e3978d7a2d9c49ad34 to your computer and use it in GitHub Desktop.
Save masaki-shimura/748cae6af79228e3978d7a2d9c49ad34 to your computer and use it in GitHub Desktop.
【デザインパターン 復習】シングルトン
/*
シングルトンクラス のサンプルプログラム
説明
インスタンスを単一にしておきたい場合に使えるデザインパターン
ポイント
・コンストラクタがprivateで隠れている
・インスタンスが一つしか作られない構造
*/
#include <iostream>
#include <string>
using namespace std;
//シングルトンクラス
class Singleton
{
public:
static Singleton* CreateInstance()
{
if(m_pInstance != nullptr)
{
cout << "すでにインスタンスがあります。" << "\n";
return m_pInstance;
}
cout << "インスタンスを生成しました。" << "\n";
m_pInstance = new Singleton();
m_pInstance->Init();
return m_pInstance;
}
static Singleton* getInstance()
{
if(m_pInstance != nullptr)
{
cout << "インスタンスを取得します" << "\n";
return m_pInstance;
}
cout << "インスタンスがなかったので生成しました。" << "\n";
m_pInstance = new Singleton();
m_pInstance->Init();
return m_pInstance;
}
static void ReleaseInstance()
{
if(m_pInstance == nullptr)
{
cout << "インスタンスがありません。" << "\n";
return;
}
cout << "インスタンスを解放しました。" << "\n";
m_pInstance->Uninit();
delete m_pInstance;
m_pInstance = nullptr;
}
void Init()
{
cout << "初期化処理..." << "\n";
}
void Uninit()
{
cout << "終了処理..." << "\n";
}
int &Port()
{
cout << "port の設定をしました。" << "\n";
return m_port;
}
string &Host()
{
cout << "host の設定をしました。" << "\n";
return m_host;
}
void dump()
{
cout << "dump 出力..." << "\n";
cout << "port :" << m_port << "\n";
cout << "host :" << m_host << "\n";
}
private:
Singleton();
static Singleton* m_pInstance;
int m_port;
string m_host;
};
Singleton* Singleton::m_pInstance = nullptr;
Singleton::Singleton():
m_port(0),
m_host("")
{
cout << "コンストラクタ呼び出し" << "\n";
}
//普通に使う時のテストコード
void drawTestCase1()
{
// Singleton クラス テストコード.
Singleton* pSingleton = Singleton::CreateInstance();
pSingleton->Port() = 33;
pSingleton->Host() = "192.168.100.1";
Singleton::getInstance()->dump();
Singleton::getInstance()->ReleaseInstance();
}
//インスタンスを複数呼んでしまった時のテストケース
void drawTestCase2()
{
// Singleton クラス テストコード.
Singleton* pSingleton = Singleton::CreateInstance();
pSingleton->Port() = 33;
pSingleton->Host() = "192.168.100.1";
pSingleton = Singleton::CreateInstance();
pSingleton->Port() = 44;
pSingleton->Host() = "192.168.255.255";
Singleton::getInstance()->dump();
Singleton::getInstance()->ReleaseInstance();
}
int main(void){
// Singleton クラス テストコード.
//普通に使う時のテスト
drawTestCase1();
//インスタンスを複数呼んでしまった時のテスト
//drawTestCase2();
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment