zoukankan      html  css  js  c++  java
  • iOS 的 Singleton 单例模式

    设计模式./-->是一种手段,一种工具.可以使代码的写起来更方便
    1. 代理设计模式(委托设计模式)

    <1>. 监听器的场合

      对象B(保姆)想监听对象A(婴儿)的一些行为

    <2>. 通知的场合

      对象A(婴儿)发生了一些行为,想通知B(保姆)[B(保姆)为代理对象]

    <3>. 有些事情,不想自己处理,可以交给别人处理

      对象婴儿发生了一些事情,不想自己处理,交给保姆处理

    2. 代理设计模式的使用场合

      当对象A发生了一些行为,想告知对象B-->[让对象B成为对象A的代理对象]

      对象B想监听对象A的一些行为-->[让对象B成为对象A的代理对象]

      当对象A无法处理某些行为的时候,想让对象B帮忙处理-->[让对象B成为对象A的代理对象]

    2. 单例设计模式

    可以保证某个类创建出来的对象只有一个

    作用是: 节省内存开销

        如果有一些数据,整个程序都用的上,只需要使用同一份资源.(保证大家访问的数据是相同的,是一致的)

        一般来说.工具类设计为单例模式.

    实现:

    非ARC模式:

    static GMTool * _gmtool = nil;

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

    {

      if (_gmtool == nil){

          static dispatch_once_t onceToken;

          dispatch_once(&onceToken, ^{_gmtool = [super allocWithZone: zone;];});       

        }

    return _gmtool;

    }

    - (oneway void) release{} //保证对象不被销毁

    -(id ) retain{ return self; }

    - (NSInteger) retainCount{ return 1;}

    - (id ) init

    { if(_gmtool == nil)

    static dispatch_once_t onceToken;

          dispatch_once(&onceToken, ^{ _gmtool  = [super init];  return _gmtool;});           

     }

    + (instancetype) shareGMTool

    {

      return  [[self alloc]init];

    }

    ARC模式:    -fobjc-arc

    static GMTool * _gmtool = nil;

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

    {

      if (_gmtool == nil){

          static dispatch_once_t onceToken;

          dispatch_once(&onceToken, ^{_gmtool = [super allocWithZone: zone;];});       

        }

    return _gmtool;

    }

    - (id ) init

    { if(_gmtool == nil)

    static dispatch_once_t onceToken;

          dispatch_once(&onceToken, ^{ _gmtool  = [super init];  return _gmtool;});           

     }

    + (instancetype) shareGMTool

    {

      return  [[self alloc]init];

    }

    UIApplication shareApplication

    NSUserDefaults standard

    UIDevice currentdevice

    NSFileManager defaultmanager

  • 相关阅读:
    java小知识点5
    java小知识点4
    java小知识点3
    编程之法:面试和算法心得(寻找最小的k个数)
    389. Find the Difference
    104. Maximum Depth of Binary Tree
    485. Max Consecutive Ones
    693. Binary Number with Alternating Bits
    463. Island Perimeter
    566. Reshape the Matrix
  • 原文地址:https://www.cnblogs.com/aunty/p/5119049.html
Copyright © 2011-2022 走看看