单例模式的错误用法_艾孜尔江撰
作者:互联网
using UnityEditor;
using UnityEngine;
/*by Alexander*/
public enum UserState
{
Online,
Chatting,
Pushing,
Offline
}
public class StateController : MonoBehaviour
{
public UserState state;
private static StateController stateController = null;
private StateController()
{
Debug.Log("Error!!!!!!!!!!!!!!");
stateController = new StateController();
Debug.Log("Error!!!!!!!!!!!!!!");
}
public static StateController getInstance()
{
if (stateController == null)
stateController = new StateController();
return stateController;
}
public void SetState(UserState newState)
{
this.state = newState;
}
}
上方的做法是错误的,请谨慎尝试,做好强制关闭Unity Editor重开的准备。
正确用法如下:
public class SingleObject {
//创建 SingleObject 的一个对象
private static SingleObject instance = new SingleObject();
//让构造函数为 private,这样该类就不会被实例化
private SingleObject(){}
//获取唯一可用的对象
public static SingleObject getInstance(){
return instance;
}
public void showMessage(){
System.out.println("Hello World!");
}
}
作者:艾孜尔江
标签:StateController,SingleObject,艾孜尔江,private,用法,static,单例,stateController,public 来源: https://blog.csdn.net/weixin_43867242/article/details/113553034