0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

【C++】Singleton(デザインパターン)

Last updated at Posted at 2025-01-28

Singletonとは?

あるクラスについて、インスタンスが単一であることを保証する設計。

  • 複数のオブジェクトで共有したいデータを保持する
  • オブジェクトを1つだけ作成することに特化している
  • 一度だけ作成することでパフォーマンスを向上できる

C++

Singleton.cpp
#include <iostream>
#include <string>

/// <summary>
/// シングルトン
/// 
/// templateで汎用性強化
/// </summary>
template<typename T>
class Singleton
{
public:
	/// <summary>
	/// デフォルトコンストラクタ
	/// 
	/// コンストラクタは絶対に呼ばない!!
	/// </summary>
	Singleton() {}

	/// <summary>
	/// インスタンスを取得する
	/// </summary>
	static T* GetInstance(void)
	{
		if (instance == nullptr)
		{
			// 初回のみ動的確保
			instance = new T;
		}

		return instance;
	}

	/// <summary>
	/// インスタンスを破棄する
	/// </summary>
	static void DeleteInstance(void)
	{
		// 削除は動的確保している時のみ
		if (instance != nullptr)
		{
			delete instance;
			instance = nullptr;
		}
	}

private:
	static T* instance;
};
template<typename T>
T* Singleton<T>::instance = nullptr;

class Sample
	: public Singleton<Sample>
{
	// friend : privateへアクセス可能にする
	friend class Singleton<Sample>;

public:
	/// <summary>
	/// 出力
	/// </summary>
	/// <returns>出力結果</returns>
	inline std::string Output(void)
	{
		return "シングルトン";
	}
};

int main(void)
{
	Sample* sample = Sample::GetInstance();

	std::cout << sample->Output() << std::endl;

	Sample::DeleteInstance();

	return 0;
}

C#

Singleton.cs
using System;

/// <summary>
/// シングルトン
/// 
/// ジェネリックで汎用性強化
/// where T : new()はインスタンス化の保証
/// </summary>
public class Singleton<T> where T : new()
{
    private static T instance;

    /// <summary>
	/// デフォルトコンストラクタ
    /// </summary>
    public Singleton() { }

    /// <summary>
	/// インスタンスを取得する
	/// </summary>
    public static T GetInstance
    {
        get
        {
            // 初回のみ動的確保
            return instance ??= new T();
        }
    }
}

// 派生クラス
public class Sample : Singleton<Sample>
{
    /// <summary>
    /// 出力
    /// </summary>
    public string Output
    {
        get
        {
            return "シングルトン";
        }
    }
}

public class Program
{
    static void Main()
    {
        // 動的確保
        Sample sample = Sample.GetInstance;

        // 出力
        Console.WriteLine(sample.Output);
    }
}
0
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?