近期热门
粉丝5
关注 0
获赞 0
unity-设计模式-单例模式

[U3D] unity-设计模式-单例模式

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

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

简单来说单例在项目中的使用,方式可以如下:[C#] [color=rgb(51, 102, 153) !important]纯文本查看 [color=rgb(51, 102, 153) !important]复制代码
[color=white !important][backcolor=rgb(108, 226, 108) !important]
[color=white !important]?

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;

    }

}







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

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


[C#] [color=rgb(51, 102, 153) !important]纯文本查看 [color=rgb(51, 102, 153) !important]复制代码
[color=white !important][backcolor=rgb(108, 226, 108) !important]
[color=white !important]?

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中只能在主线程中进行调用。所以网络多线程方面会产生单例的不唯一性,在这里就可以忽略了。

0
点赞
0
打赏
0
添加到收藏夹

0

点击复制链接

使用微信扫码分享
一次扣10个券
全部评论2
您需要登录后才可以回帖 登录

好好好哈哈哈呵呵呵
8年前
回复

使用道具 举报

好好好哈哈哈呵呵呵
8年前
回复

使用道具 举报

您当前使用的浏览器IE内核版本过低会导致网站显示错误

请使用高速内核浏览器或其他浏览器