Unity Single-Case mode

Source: Internet
Author: User

Reproduced quoted csdn waves Gao Soft, Yan and other Daniel's blog &

Https://www.cnblogs.com/liaoguipeng/p/5130144.html

46906217----Good suggestions!

Singleton mode:(singleton pattern), simply say that the class instance in memory only one;

The summary of the two simple types is as follows:

I. Write a script and then drag and drop the script onto an object in the scene, and be careful to drag it to the scene once and we know that once the script is given to an object in the scene,

becomes the script component, the component is the object, so instances of this class have only one in the scene, so in a sense the script component is a singleton.

There are two ways to access this kind of singleton:

1.getcomponent method;

2. In the game, often in order to get convenient, the more easy way to use the following (Xuhaitao.instance), using this method to pay attention to three points, in the scene and only one of the script components of the class,

The other thing is that the object that the script component is attached to must be active in the scene, otherwise the null pointer exception is reported, and the last point is to put the Instance=this code in the Awake function.

Do not put in the start function--prevent this singleton from being instantiated when called in other classes, and report an empty error:

If the script inherits Monobehavior, it is simpler to use the singleton.

Just add a sentence instance = this in Awake ();

Ii.

1. methods of public static methods

 public  class   assetloader:monobehaviour{ private  static   Assetloader instance;  private  Assetloader () {} //  public  static   Assetloader getinstance () { if  (Instance = = null   = new   Assetloader ();     return   instance; }

2. methods for public static properties

 Public classassetloader:monobehaviour{Private StaticAssetloader instance; PrivateAssetloader () {}//prohibit external access to an instance of this class by means of new     Public StaticAssetloader Instance {Get        {            if(Instance = =NULL) {instance=NewAssetloader (); }            returninstance; }    }

Further introductions and uses:

One, the advantages of a single case model

    1. The core of the singleton mode is that for a singleton class, only one instance exists in the system at the same time, and the instance is easily accessed by the outside world.
    2. means that there is only one instance in memory, which reduces the memory overhead;

Second, the characteristics of the single case model

    1. Only one instance exists;
    2. Provides a unified external access interface so that the unique instance of the singleton can be accessed globally;
    3. Self-instancing (private constructors, which are not allowed to be instantiated by the outside world).

Third, the use of single-case mode

    1. Resource Manager, loading and unloading of resource object data (stateless objects that do not need to be instantiated);
    2. Single Client connection server, etc.;
    3. The life cycle is the object that will never be destroyed in the game.

Four, single-case mode attention point

    1. Pay attention to the thread security problem, in the case of multithreading, high concurrency, may produce multiple instances at the same time, violating the singleton mode.
    2. If you overuse the singleton pattern in unity, it will lead to very high code coupling, the coupling between scripts and scripts, and the subsequent expansion of the code becomes cumbersome. A developer who relies too much on a singleton can not be a good developer and will not be exposed to more good design patterns. Personal recommendation ECS Entity-component programming.
    3. In unity, there is no need to consider multithreading, unity has only one main thread and multiple helper threads, without multithreading concurrency problems.
    4. Controlling the generation and destruction of game objects is not recommended by using the singleton mode, which can be issued via the main game logic ingame, manage the update yourself, and use the factory to create and destroy objects.

The common mode of the single case pattern

    1. Lazy mode (most commonly used)

      1.1 Provide private constructors;

      1.2 Self-instantiation;

      1.3 Provides a unique instance, and provides a global static access interface to access the instance;

/// <summary>///Normal Mode/// </summary> Public classsingleton{Private StaticSingleton _instance =NULL; PrivateSingleton () {} Public StaticSingleton getinstance () {if(_instance = =NULL) {_instance=NewSingleton (); }        return_instance; }}

2. A Hungry man mode

2.1 In this class, the unique instance is instantiated in advance by itself;

2.2 Provide a unique access interface (static method), access to a unique instance of the pre-instantiation;

2.3 Private constructors;

/// <summary>    ///a hungry man single-case mode/// </summary>     Public classSingleton {//pre-Instantiate yourself, define your own unique instance internally, for internal use only//        Private ReadOnly StaticSingleton Instance =NewSingleton (); PrivateSingleton () {//Do Something        }        //provides a static method of external access to access the internal unique instance//         Public StaticSingleton getinstance () {returnInstance; }    }

3. Dual lock mode (resolves thread safety issues)

3.1 Ensure only unique instances exist in multiple threads

/// <summary>///Double Lock single case mode/// </summary> Public classsingleton{Private StaticSingleton _instance =NULL; Private Static ReadOnly Object_syslock =New Object(); PrivateSingleton () {} Public StaticSingleton getinstance () {//The class has never been instantiated at the very beginning when it does not exist.//        if(_instance = =NULL)        {            //lock State to continue searching for instances of this class//            Lock(_syslock) {//if not present, instantiate an instance in a locked state//                if(_instance = =NULL) {_instance=NewSingleton (); return_instance; }                Else  //locked state, there is an instance of that class, which returns directly//                {                    return_instance; }            }        }        //The instance itself already exists and returns directly//        return_instance; }}



Public properties
PublicSealedClass Singleton
{
PrivateStaticvolatile Singleton instance;
PrivateStaticObject SyncRoot =New Object ();
PrivateSingleton () {}
PublicStatic Singleton Instance
{
Get
{
if (instance = null)  
          {
            lock (syncRoot)  
            {
               if (instance = null)  
                   instance = new Singleton ();
           }
        }
         return instance;
     }
  }
}

4. Generic Singleton mode

In one case, we might need to use more than one Singleton pattern class, or even more. So at this point, using the generic singleton pattern template to implement the singleton pattern, we can have two different ways to implement it:

  • 4.3.1 First we look at the generic template, we constrain the generic class, T can only be a class, and there is a public parameterless constructor, the code is as follows:
    Using system;using Unityengine;public class singletonprovider<t> where T:class, new () {    private Singletonprovider ()    {    }    private static T _instance;    Object for lock block    private static readonly Object _synclock = new Object ();    public static T Instance    {        get        {            if (_instance = = null)            {                lock (_synclock)                {                    if ( _instance = = null)                    {                        //If T class has a private constructor, then you cannot use singletonprovider<t> to instantiate the new T ();                        _instance = new T ();                        For testing, if the T type creates an instance, it outputs its type name                        Debug.Log ("{0}: Create singleton object" + typeof (T). Name);            }}} return _instance;        }        set {_instance = value;}}    }
      • 4.3.2 then we define a network connection class NetIO, using a generic t substitution in a singleton class to use for a specific network connection class:
        1. Using a specific class instead of generics, use a generic singleton to provide a singleton implementation of a class that provides a unique instance to that specific class:
        2. The field netiocreatetime is defined in the specific class to store the time that the class is instantiated, and the next step is to analyze whether the class instance is a unique instance, with the following class code:
          public class NetIO {public    static NetIO getinstance ()    {        return singletonprovider<netio>. Instance;    }    Public NetIO ()    {        this.netiocreatetime = DateTime.Now;    }    Public DateTime netiocreatetime    {        get {return _ct;}        set {_ct = value;}    }    Private DateTime _ct;}
        3. Call this class in the update parameter in unity to output the class creation time
          public void Update ()    {        Debug.Log (netio.getinstance (). netiocreatetime);    }
        4. The test results are as follows:
        5. All creation times are consistent, proving that the class provides a generic override in a singleton class, achieves the effect of a singleton pattern, and provides unique instance access to the class

Unity Single-Case mode

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.