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

    SigleTon.h文件

    #import <Foundation/Foundation.h>

    @interface SigleTon : NSObject<NSCopying>

    +(SigleTon *)shareInstance;

    @end

    SigleTon.m文件

    #import "SigleTon.h"

    @implementation SigleTon

    static SigleTon *sigleton;

    +(SigleTon *)shareInstance

    {

        if (sigleton==nil)

        {

            sigleton=[[SigleTon alloc] init];

        }

        return sigleton;

        

    }

    //重写allocWithZone的方法

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

    {

        if (sigleton==nil)

        {

            sigleton=[super allocWithZone:zone];

        }

        return sigleton;

    }

    //重写copyWithZone的方法

    -(id)copyWithZone:(NSZone *)zone

    {

        return self;

    }

    @end

    main.m文件

            SigleTon *sing1=[SigleTon shareInstance];

            SigleTon *sing2=[SigleTon shareInstance];

            SigleTon *sing3=[[SigleTon alloc] init];;

            SigleTon *sing4=[SigleTon new];

            SigleTon *sing5=[sing4 copy];

           

            NSLog(@"%p",sing1);

            NSLog(@"%p",sing2);

            NSLog(@"%p",sing3);

            NSLog(@"%p",sing4);

            NSLog(@"%p",sing5);

    运行结果如下

    2016-03-04 22:27:41.643 单例模式[2166:239114]  0x100106bf0

    2016-03-04 22:27:41.643 单例模式[2166:239114] 0x100106bf0

    2016-03-04 22:27:41.643 单例模式[2166:239114] 0x100106bf0

    2016-03-04 22:27:41.644 单例模式[2166:239114] 0x100106bf0

    2016-03-04 22:27:41.644 单例模式[2166:239114] 0x100106bf0

    由结果可以看出,每一个对象的地址都是一样的,保证了每一个实例的对象都是同一个

    单例模式的要点:

    一是某个类只能有一个实例;

    二是它必须自行创建这个实例;

    三是它必须自行向整个系统提供这个实例。

  • 相关阅读:
    js 跳转链接
    reg.test is not a function 报错
    html中button自动提交表单?
    mysql主从复制及双主复制
    nginx反向代理后端web服务器记录客户端ip地址
    mysql多实例-主从复制安装
    LVS+Keepalived高可用负载均衡集群架构实验-01
    debug调试
    常用网站总结
    项目部署
  • 原文地址:https://www.cnblogs.com/layios/p/5243696.html
Copyright © 2011-2022 走看看