zoukankan      html  css  js  c++  java
  • 自定义 一个单例

    单例是一种重要的概念,它是一种极其便利的设计模式

    #import <Foundation/Foundation.h>

    @interface DanLi : NSObject

    {

        NSString *someProperty;

    }

    @property (nonatomic,retain) NSString *someProperty;

    + (id)sharedDanli;

    @end

    #import "DanLi.h"

    @implementation DanLi

    @synthesize someProperty;

    + (id)sharedDanli

    {

        static DanLi *myDanli = nil;

        

        /*通过GCDdispath_once方法,我们确保sharedMyManager方法只会被创建一次。这是线程安全的,你无需担心什么。*/

         

         

        static dispatch_once_t onceToken;

        dispatch_once(&onceToken, ^{

            myDanli = [[self alloc] init];

        });

        return myDanli;

    }

    /*不想用GCG,也可以这样实现sharedManager方法:

     -GCD 代码

     + (id)sharedDanli {

     @synchronized(self) {

     if (myDanli == nil)

     sharedMyManager = [[self alloc] init];

     }

     returnsharedMyManager;

     }*/

    // 这样来使用单例  MyManager *sharedManager = [MyManager sharedManager];

    - (id)init

    {

        if (self = [super init]) {

            someProperty =@"Default Property Value";

        }

        returnself;

    }

    -(void)dealloc {

        

        // Should never be called, but justhere for clarity really.

    }

    @end

  • 相关阅读:
    python征程1.4(初识python)
    python征程1.3(初识python)
    python征程1.2(初识python)
    python征程1.1(初识python)
    什么是servlet
    什么是JavaBean
    基于Ajax的前后端分离
    项目开发流程
    项目框架和项目架构
    Java中使用 foreach 操作数组
  • 原文地址:https://www.cnblogs.com/chenhaosuibi/p/3439394.html
Copyright © 2011-2022 走看看