zoukankan      html  css  js  c++  java
  • 单例的实现(完整版代码)

    #import "XMGTool.h"

     

    static XMGTool * _instance;//静态变量保证了单例的唯一性,静态变量是程序一开始就存在的

     

    @interface XMGTool ()<NSCopying, NSMutableCopying>

     

    @end

     

    @implementation XMGTool

     

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

    {

        static dispatch_once_t onceToken;

        dispatch_once(&onceToken, ^{

            _instance = [super allocWithZone:zone];

        });

        return _instance;

    }

     

    +(instancetype)shareTool

    {

        return [[self alloc]init];

    }

     

    - (nonnull id)copyWithZone:(nullable NSZone *)zone {

        return _instance;

    }

     

    - (nonnull id)mutableCopyWithZone:(nullable NSZone *)zone {

        return _instance;

    }

     

    @end

     

     

    外界的调用:

     

      XMGTool *t1 = [[XMGTool alloc]init];

       XMGTool *t2 = [[XMGTool alloc]init];

       XMGTool *t3 = [XMGTool shareTool];

       XMGTool *t4 = [t1 mutableCopy];

        

        NSLog(@" %@-- %@-- %@--- %@",t1,t2,t3,t4);

     

    打印结果

    <XMGTool: 0x6000011b2e30>--

    <XMGTool: 0x6000011b2e30>--

    <XMGTool: 0x6000011b2e30>---

    <XMGTool: 0x6000011b2e30>

  • 相关阅读:
    codeforces 869E. The Untended Antiquity(二维树状数组,随机化)
    bzoj 3083: 遥远的国度(树上换根操作,树剖+询问整个子树)
    hdu 5534 Partial Tree(dp+降唯,好题)
    AtCoder Regular Contest 075 E
    hihocoder 1387 A Research on "The Hundred Family Surnames"(树,lca,求同一颜色的直径)
    hdu 5458 Stability(生成树,树链剖分,好题)
    推荐一套个人ui组件库
    回望2019,期盼2020
    如何从产品的角度对待自己的博客
    致一名迷茫的我
  • 原文地址:https://www.cnblogs.com/dashengios/p/10420541.html
Copyright © 2011-2022 走看看