不同平台单例模式实现方式

来源:互联网 发布:搞笑段子 知乎 编辑:程序博客网 时间:2024/05/02 13:09

单例模式是一种很基本很常用的设计模式,游戏开发中用的非常多。继承下面的类即可将一个类变成单例类:

一. IOS中的单例模式

IOS中实现单例可以定义static变量实现,但更好的方法是使用线程保证类的实例化语句只执行一次即可:

////  SingletonClass.h//  JXHDemo////  Created by Xinhou Jiang on 16/7/31.//  Copyright © 2016年 Jiangxh. All rights reserved.//#import <Foundation/Foundation.h>@interface SingletonClass : NSObject/** * class单例 */+ (SingletonClass *)Ins;@end

////  SingletonClass.m//  JXHDemo////  Created by Xinhou Jiang on 16/7/31.//  Copyright © 2016年 Jiangxh. All rights reserved.//#import "SingletonClass.h"@implementation SingletonClass/** * class单例 */+ (SingletonClass *)Ins {    static dispatch_once_t once;    static id sharedInstance;    dispatch_once(&once, ^{        // 只实例化一次        sharedInstance = [[self alloc] init];    });    return sharedInstance;}@end
单例类使用示例:

// 可在整个工程中调用如下代码:[SingletonClass Ins].name = @"sharedInstnce";NSString *name = [SingletonClass Ins].name;

二.Unity中的单例模式

unity中继承下面类的C#脚本可变成单例脚本:

using UnityEngine;/* * 泛型单例类,只允许有一个实例 */public class Singleton<T> : MonoBehaviour where T : Singleton<T>{    //静态单一实例    protected static T _instance;    //获取实例的接口    public static T Ins    {        get        {            return _instance;        }    }    //初始化单例    protected virtual void Awake()    {        _instance = (T)this;    }    //销毁实例    protected virtual void OnDestroy()    {        _instance = null;    }}


1 0
原创粉丝点击