zoukankan      html  css  js  c++  java
  • 单例

    1.单例的介绍:

    单例模式是一种常用的设计模式,在应用这个模式时,单例对象的类必须保证只有一个实例存在。通过单例模式可以保证系统中一个类只有一个实例而且该实例易于外界访问,从而方便对实例个数的控制并节约系统资源。如果希望在系统中某个类的对象只能存在一个,单例模式是最好的解决方案。

    2.单例的创建:

    (1).h文件

    #import <Foundation/Foundation.h>

     @interface MGSingleMethod : NSObject

    {

        //传递的值

        NSString *_name;

    }

     @property (nonatomic,copy) NSString *name;

     //通过类方法得到这个类

    + (MGSingleMethod *)shareSingleMethod;

     + (void)releaseSingle;

     @end

    (2).m中的实现

     #import "MGSingleMethod.h"

    @implementation MGSingleMethod

    //1.设置静态的对象

    static MGSingleMethod *single = nil;

     + (MGSingleMethod *)shareSingleMethod {

        //2.线程安全,这样的创建只有一个线程进入,只能创建一个对象

        @synchronized(self) {

            

            single = [[MGSingleMethod alloc] init];

        }

        

        return single;

    }

    //为了保证对象的唯一性,重写allocwithzone方法

    + (instancetype)allocWithZone:(struct _NSZone *)zone {

        if (single == nil) {

            single = [super allocWithZone:zone];

        }

        return single;

    }

    //释放对象

    + (void)releaseSingle {

        if (single != nil) {

            single = nil;

        }

    }

    @end

    3.单例的应用:

    在用到单例的类中,引入单例的h文件,然后通过类方法创建单例对象,然后可以对要传递的值进行赋值,然后在应用这个值的类,同样通过类方法创建单例,直接引入传递的值即可。

  • 相关阅读:
    智能实验室-结构化存储浏览器(SSExplorer) 1.5.0.150
    智能实验室-杀马(Defendio) 3.1.0.681
    智能实验室-结构化存储浏览器(SSExplorer) 1.6.0.160
    IT餐馆—第八回 三十
    使用Silverlight Toolkit 绘制图表区域图和冒泡图
    IT餐馆—第十二回 软培
    IT餐馆—第四回 离职
    IT餐馆—第一回 前言
    IT餐馆—第十回 潜伏
    IT餐馆—第十三回 重构
  • 原文地址:https://www.cnblogs.com/zhangxiansen/p/5740007.html
Copyright © 2011-2022 走看看