• 单例模式的错误用法


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

    作者:艾孜尔江

  • 相关阅读:
    problem in Sourcetree
    Get started with Sourcetree
    IIS application pool access desktop denied
    结构型模式 适配器模式
    结构型模式 装饰模式
    结构型模式 代理模式
    创建型模式 原型模式
    创建型模式 建造者模式
    创建型模式 抽象工厂
    设计模式的六大原则
  • 原文地址:https://www.cnblogs.com/ezhar/p/14332800.html
Copyright © 2020-2023  润新知