genice26 发表于 2015-2-4 17:05

unity-设计模式-单例模式

今天继续学习蛮牛教育上的水浒卡牌项目是提到过设计模式,我就查了一下,把我查到了分享给大家。设计模式主要分为三类:1. 创建者模式2.结构性模式3.行为模式
今天我们要说的就是GOF23中设计模式里面的一个,叫做单例模式。在他的字典里,不允许有第二个自己存在,要保证实例唯一。他的一般解释就是,保证一个类只有一个实例,并提供一访问他的全局访问点。单例模式因为封装他的唯一实例,他就可以严格的控制客户怎样访问他以及何时访问他。

下面我们就设计模式在引擎开发中的使用来做一些简单说明。

简单来说单例在项目中的使用,方式可以如下: 纯文本查看 复制代码
?

01
02
03
04
05
06
07
08
09
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
using UnityEngine;

using System.Collections;

/**
蛮牛教育
By-Robin
*/

public class SigletonOnlyOne : MonoBehaviour

{

    public static SigletonOnlyOne instance;



    public void Start()

    {

      if (instance==null)

      {

            instance = this;

      }

    }



    public string ShowMsg(string msg)

    {

      return msg;

    }

}








优点:不需要重构什么,直接编码。方便其他类使用。

缺点:每个要实现单例的类都需要手动写上相同的代码,代码重复对我们来说可不是好事情。同时需要把实现单例的类手动绑定到游戏对象上才可以使用。


纯文本查看 复制代码
?

01
02
03
04
05
06
07
08
09
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
using UnityEngine;

using System.Collections;

/**
蛮牛教育
By-Robin
*/

/// <summary>

/// 定义单例模板基类。

/// </summary>

/// <typeparam name="T"></typeparam>

public class Singleton<T> : MonoBehaviour where T : MonoBehaviour

{

private static T instance;



    public static T Instance

    {

      get

      {

            if (instance == null)

            {

                GameObject singleton = new GameObject();

                singleton.name = "蛮牛教育";

                instance = singleton.AddComponent<T>();

            }

            return instance;

      }

    }



    public void OnApplicationQuit()

    {

      instance = null;

      Debug.Log("quit");

    }

}









优点:不需要手动绑定单例到游戏对象就可以使用。

缺点:这些都是游戏对象,在unity3d中只能在主线程中进行调用。所以网络多线程方面会产生单例的不唯一性,在这里就可以忽略了

wll123321 发表于 2017-2-22 14:00

很不错

心境 发表于 2017-2-22 14:37

楼主是超人

fengnv314322 发表于 2017-2-22 14:37

难得一见的好帖

laughing_sir 发表于 2017-2-22 14:44

很好哦

wll123321 发表于 2017-2-22 14:06

LZ真是人才

pandara_wen 发表于 2017-4-14 08:38

很不错

pandara_wen 发表于 2017-4-14 08:54

好帖就是要顶

weihon 发表于 2017-4-14 08:54

很好哦

肥马时代 发表于 2017-4-14 09:09

不错不错
页: [1] 2 3 4 5 6 7 8 9 10
查看完整版本: unity-设计模式-单例模式