单例模式的错误用法

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!");
   }
}


作者:艾孜尔江

posted @ 2021-01-26 22:39  艾孜尔江  阅读(138)  评论(0编辑  收藏  举报