【发布时间】:2021-10-18 09:47:01
【问题描述】:
我正在创建一个Manager 类,它使用 C# 接口实现单例模式。
我想出了一个结构,将单例模式应用于Manager 类,将其继承给我的孩子,并扩展功能。
但是,如果我尝试从其他类访问它,我只能访问Manager 类。
我觉得我需要修改代码或结构,我该怎么办?
ISingleton.cs
using System;
using System.Collections.Generic;
using UnityEngine;
public interface ISingleton<T> where T : class
{
void SetSingleton(T _classType, GameObject _obj);
T GetInstance();
}
Singleton.cs
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public abstract class Singleton<T> : MonoBehaviour , ISingleton<T> where T: class
{
public static T instance = default;
public void SetSingleton(T _class, GameObject _obj)
{
if (instance is null) instance = _class;
else if(instance.Equals(_class))
{
Debug.LogError("Unexpected Instancing Singleton Occuired! from " + gameObject.name);
Destroy(_obj);
return;
}
DontDestroyOnLoad(_obj);
}
public T GetInstance()
{
return instance;
}
}
Manager.cs
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class Manager : Singleton<Manager>,IManager
{
public int data;
protected virtual void Awake()
{
Initialize();
}
public virtual void Initialize()
{
SetSingleton(this,this.gameObject);
}
}
游戏管理器
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class GameManager : Manager
{
public int HP,point;
protected override void Awake()
{
Initialize();
}
public override void Initialize()
{
SetSingleton(this, this.gameObject);
}
private void StartGame() => print("GameStart");
private void PauseGame() => print("Game Paused");
private void QuitGame() => Application.Quit();
}
下面是我的代码的粗略结构。
【问题讨论】:
-
你不能通过使用接口来真正强制单例模式,因为没有什么可以阻止某人添加一个构造函数来让他们创建一个新实例。此外,
GetInstance方法必须是static,这意味着它不能构成接口的一部分。
标签: c# unity3d design-patterns interface singleton