Unity3d设计模式之单例模式
来源:互联网 发布:网络舆论论文 编辑:程序博客网 时间:2024/05/16 16:02
单例模式我相信是所有设计模式之中运用最广泛的设计模式之一。
今天我们就来看看在unity中如何使用单例模式,在unity中,我们分两种单例,一种是继承monobehavior的单例,一种是普通单例。
单例模式的定义是:保证一个类只有一个实例,并且提供一个访问它的全局访问点。单例对象的类必须保证只有一个实例存在。在我们的场景中,全局脚本的对象只会创建一次,保证单例,然后它(全局单例类)提供给各个脚本访问单例对象的方法,并且所有其他脚本的公共数据都会存储在全局单例脚本中。
1.MonoBehavior单例
其实在unity中,如果脚本是继承monobehavior,那么使用起单例来更加简单。
只需要在Awake()里面,添加一句instance = this;
1
2
3
4
5
6
7
8
9
10
11
12
13
14
using
UnityEngine;
using
System.Collections;
public
class
test2 : MonoBehaviour {
public
static
test2 instance;
// Use this for initialization
void
Awake () {
instance =
this
;
}
// Update is called once per frame
void
Update () {
}
}
其他脚本要调用的时候,直接:
public test2 name;
name = test2.instance;
2.普通类的单例
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
using
UnityEngine;
using
System.Collections;
public
class
test2 {
private
static
test2 instance;
public
static
test2 Instance
{
get
{
if
(
null
== instance)
instance =
new
test2();
return
instance;
}
set
{ }
}
}
那么问题也就来了,细心的读者会发现,如果项目中有很多个单例,那么我们就必须每次都写这些代码,有什么办法可以省去这些不必要的代码呢?有,那就是面向对象最重要的思想:继承。
今天我们就来学习下,自己封装一个单例类,只要项目中用到单例的话,就从这个单例类继承,把它变成单例。
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
public
class
Singleton<T>
where
T :
new
()
{
private
static
T s_singleton =
default
(T);
private
static
object
s_objectLock =
new
object
();
public
static
T singleton
{
get
{
if
(Singleton<T>.s_singleton ==
null
)
{
object
obj;
Monitor.Enter(obj = Singleton<T>.s_objectLock);
//加锁防止多线程创建单例
try
{
if
(Singleton<T>.s_singleton ==
null
)
{
Singleton<T>.s_singleton = ((
default
(T) ==
null
) ? Activator.CreateInstance<T>() :
default
(T));
//创建单例的实例
}
}
finally
{
Monitor.Exit(obj);
}
}
return
Singleton<T>.s_singleton;
}
}
protected
Singleton()
{
}
阅读全文
0 0
- Unity3d设计模式之单例模式
- Unity3D设计模式之单例模式
- Unity3d设计模式之单例模式
- unity3d中的设计模式之<单例模式>
- 【unity】Unity3d设计模式之单例模式
- Unity3d之设计模式(一)单例模式
- Unity3D设计模式之单例模式(1)
- Unity3d之设计模式(一)单例模式
- 设计模式之 单例设计模式
- 设计模式之 单例设计模式
- 设计模式之单例设计模式
- 设计模式之-----------单例设计模式
- 设计模式之:单例设计模式
- 设计模式之单例设计模式
- 设计模式之单例设计模式
- 设计模式之单例设计模式
- 设计模式之单例设计模式
- 设计模式之单例设计模式
- 九大排序之——插入排序
- 数据库锁机制
- 深入理解JavaScript系列(43):设计模式之状态模式
- 网络编程基础
- C# 如何在编译时将 dll 复制到 bin\Release 目录下
- Unity3d设计模式之单例模式
- Datagrid里面如何捕获前一页下一页最后页最前页的事件?
- 深入理解JavaScript系列(44):设计模式之桥接模式
- Openssh移植到Android系统的步骤
- CFgym:Digits Permutation(DFS)
- Repeater中OnItemDataBound使用方式
- java 反射的理解和使用
- Android之二维码生成与识别 读取相册
- 深入理解JavaScript系列(45):代码复用模式(避免篇)