美文网首页
六种传值方式之单例模式

六种传值方式之单例模式

作者: fuxi | 来源:发表于2016-08-21 12:04 被阅读0次

原文网址:[http://www.cnblogs.com/lyanet/archive/2013/01/11/2856468.html]

单例模式:

此单例模式的类只有一个实例,能够自行实例化并向系统提供这个实例。该类称为单例类。

1.特点:

1.该类只能有一个实例
2.必须自行创建此实例
3.自行向系统提供该实例

2.优点:

1.访问的实例相同且唯一:因为单例模式不允许其他对象在进行这个单例类的实例化。
2.灵活性:因为类控制了实例化过程,所以类可以更加灵活修改实例化过程。

3.创建单例模式的三个步骤:

1、为单例对象实现一个静态实例,并初始化,然后设置成nil,
2、实现一个实例构造方法检查上面声明的静态实例是否为nil,如果是则新建并返回一个本类的实例,   
3、重写allocWithZone方法,用来保证其他人直接使用alloc和init试图获得一个新实力的时候不产生一个新实例,      

举例(使用单例模式实现A、B两个页面之间的传值):
思路:
A页面:

//1. 定义一个静态全局变量
static RootViewController *instance = nil;
//2. 实现类方法---实例构造检查静态实例是否为nil
+ (instancetype) sharedInstance { 
        @synchronized(self) { 
              if (instance == nil) { 
                    //如果为空,初始化单例模式 
                    instance = [[RootViewController alloc] init]; 
                } 
          } 
         return instance;
  }
 //3.重写allocWithZone方法
 //说明:这里的的复写目的是防止用户无意之间采用[[RootViewController alloc] init]进行初始化
  + (instancetype) allocWithZone:(struct _NSZone *)zone {                       
      @synchronized(self) { 
             if (instance == nil) { 
                   //说明:这里的实例是进行内存的分配 
                   instance = [super allocWithZone: zone]; 
              }
         } 
      return instance;
    }

B页面

  //button的响应事件里实现值得传递
   - (void) backAction: (UIButton *) button { 
        //1) 取值
         UITextField *textField = (UITextField *)[
              self.view viewWithTag:2000]; 
        //2) 通过单例模式修改值 
        RootViewController *rootViewController = [RootViewController sharedInstance]; 
        rootViewController.label.text = textField.text; 
        //3) 关闭模态视图 
        [self dismissViewControllerAnimated:YES completion:nil];
  }

源代码地址:
https://github.com/zoushuyue/SYSingletonByValue

相关文章

网友评论

      本文标题:六种传值方式之单例模式

      本文链接:https://www.haomeiwen.com/subject/dftwsttx.html