C++ 单例模式

#include "iostream"

using namespace std;

class AloneClass {
public:
	static AloneClass* Instance() {
		if (aloneClass == nullptr) {
			aloneClass = new AloneClass();
		}
		return aloneClass;
	}
	void PrintS() {
		cout << 234 << endl;
	}

private:
	AloneClass() {

	}
	~AloneClass();
	AloneClass(const AloneClass& alone);
	AloneClass& operator=(const AloneClass& alone);

private:
	static AloneClass* aloneClass;
};

AloneClass* AloneClass::aloneClass = nullptr;

int main() {
	AloneClass::Instance()->PrintS();

	return 0;
}

C++ 单例模式_第1张图片

这种情况是不是多线程的情况,多线程若需要单例,则需要调用call_once函数

#include "iostream"

using namespace std;

template
class SingleClass
{
public:
	static Type* Instance() {
		if (singleClass == nullptr) {
			singleClass = new Type();
		}
		return singleClass;
	}
	
private:
	SingleClass() {}
	~SingleClass() {}
	SingleClass(const Type& single) {}
	SingleClass& operator= (const Type& single) {}
private:
	static Type* singleClass;
};

template
Type* SingleClass::singleClass = nullptr;

class B {
	friend SingleClass;
public:
	void Print() {
		cout << 1234 << endl;
	}
private :
	B() {}
	~B() {}
	B(const B& b) {}
	B& operator=(const B& b) {}
};

int main() {
	SingleClass::Instance()->Print();

	return 0;
}

修改成为模板形式

C++ 单例模式_第2张图片

C++ 单例模式_第3张图片


UE版本

// Copyright Epic Games, Inc. All Rights Reserved.

#pragma once

#include "CoreMinimal.h"
#include "mutex"

template
class SingleClass
{
public:
	static Type* Instance() {
		std::lock_guard lockGuard(mtx);
		if (singleClass == nullptr) {
			singleClass = NewObject();
		}
		return singleClass;
	}
	
private:
	SingleClass() {}
	~SingleClass() {}
	SingleClass(const Type& single) {}
	SingleClass& operator= (const Type& single) {}
	static std::mutex mtx;
private:
	static Type* singleClass;
};

template
Type* SingleClass::singleClass = nullptr;
template
std::mutex SingleClass::mtx;

这里加了锁,防止多线程造成两次调用Instance实例出两个实例

// Copyright Epic Games, Inc. All Rights Reserved.

#pragma once

#include "CoreMinimal.h"
#include "SingleClass.h"
#include "GameFramework/Actor.h"
#include "CreateActorFactory.generated.h"

UCLASS()
class ACreateActorFactory : public AActor
{
	GENERATED_BODY()
		friend class SingleClass;
public:
	void Print();
private:
	ACreateActorFactory() {}
	~ACreateActorFactory() {}
};
// Copyright Epic Games, Inc. All Rights Reserved.

#include "CreateActorFactory.h"

void ACreateActorFactory::Print() {
	GEngine->AddOnScreenDebugMessage(-1, 10.f, FColor::Red, "324");
}
// Copyright Epic Games, Inc. All Rights Reserved.

#include "ActorBase.h"
#include "SingleClass.h"
#include "CreateActorFactory.h"

AActorBase::AActorBase() {

}

void AActorBase::BeginPlay() {
	Super::BeginPlay();

	SingleClass::Instance()->Print();
}

C++ 单例模式_第4张图片

你可能感兴趣的:(c++,单例模式,javascript)