zoukankan      html  css  js  c++  java
  • [IOS 下重温设计模式] Singleton

    View Code
    @interface Singleton : NSObject 
    {

    }

    + (Singleton *) sharedInstance;

    - (void) operation;


    @end
    View Code
    #import "Singleton.h"


    @implementation Singleton


    static Singleton *sharedSingleton_ = nil;

    - (void) operation
    {
    // do something
    NSLog(@"Singleton");
    }

    + (Singleton *) sharedInstance
    {
    if (sharedSingleton_ == nil)
    {
    sharedSingleton_ = [NSAllocateObject([self class], 0, NULL) init];
    }

    return sharedSingleton_;
    }


    + (id) allocWithZone:(NSZone *)zone
    {
    return [[self sharedInstance] retain];
    }


    - (id) copyWithZone:(NSZone*)zone
    {
    return self;
    }

    - (id) retain
    {
    return self;
    }

    - (NSUInteger) retainCount
    {
    return NSUIntegerMax; // denotes an object that cannot be released
    }

    - (void) release
    {
    // do nothing
    }

    - (id) autorelease
    {
    return self;
    }

    @end

    =============================

    View Code
    @interface MySingleton : Singleton
    {

    }

    @end
    View Code
    @implementation MySingleton

    - (id) init
    {

    return self;
    }

    - (void) operation
    {
    // do something
    NSLog(@"MySingleton");
    }

    @end

    =============================

    client:

    View Code
      Singleton *s = [MySingleton sharedInstance];

    [s operation];






  • 相关阅读:
    腾讯一面有感(移动开发岗位)
    kafka 在java中的使用
    Kafka史上最详细原理总结下
    java jdk原生的http请求工具类
    kafka(一)
    MySQL:互联网公司常用分库分表方案汇总
    密码正则
    springboot 打war包
    oracle存储过程的一些使用
    对象的深度克隆
  • 原文地址:https://www.cnblogs.com/GnagWang/p/2219959.html
Copyright © 2011-2022 走看看