zoukankan      html  css  js  c++  java
  • 单例

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

        iOS中最常见的单例就是UIApplication,UIWindow.

    单例的实现步骤:

        1> 重写allocWithZone方法;

        allocWithZone方法是对象分配内存空间时,最终会调用的方法,重写该方法,保证只会分配一个内存空间。

        2> 建立sharedXXX类方法,便于其他类访问;

    方法实现代码如下:

    #import <Foundation/Foundation.h>
    
    @interface Ticket : NSObject
    
    +(id)sharedTiket
    
    @end
    
    #import "JNInstance.h"
    
    @implementation JNInstance
    
    +(id)allocWithZone:(struct _NSZone *)zone
    {
        static Ticket *instance;
        static dispatch_once_t onceToken;
        dispatch_once(&onceToken, ^{
            instance = [super allocWithZone:zone];
            });
            return instance;
    }
    
    +(id)sharedTiket
    {
        return [self allocWithZone:nil];
    }

        dispatch_once 是线程安全的,能够做到在多线程的环境下Block中的代码只会被执行一次;

    单例模式

    优点:

        可以阻止其他对象实例化单例对象的副本,从而确保所有对象都访问唯一实例;

    缺点:

        单例对象一旦建立,对象指针是保存在静态区的,单例对象在堆中分配的内存空间,会在应用程序终止后才会被释放;

    提示:

        只有确实需要唯一使用的对象才需要考虑单例模式,不要滥用单例。

  • 相关阅读:
    MVC和MTV模式
    Do a web framework ourselves
    什么是web框架?
    12.1.2 实战演练——编写一个适用于Android系统的网页
    10.4 实战演练
    Genymotion
    Reactive Native开发环境搭建
    第10章 使用WebKit浏览网页数据
    第7章 Android中访问网络资源
    3.4 存储简单数据的利器——Preferences
  • 原文地址:https://www.cnblogs.com/liyanyan/p/6007650.html
Copyright © 2011-2022 走看看