Singleton(dispatch_once版)

On 2011年12月1日, in Objective-C, by タカ

Objective-Cのシングルトンは以前書いたけど、

dispatch_onceを使うとより簡単に書けるのでメモ。


Singleton.h

#import <Foundation/Foundation.h>

@interface Singleton : NSObject
+ (Singleton *)instance;
@end

Singleton.m

#import "Singleton.h"

@implementation Singleton

+ (Singleton *)instance {
  static Singleton *instance_ = nil;
  static dispatch_once_t predicate;
  dispatch_once(&predicate, ^{
    instance_ = [[self alloc] init];
  });
  return instance_;
}

@end

Singleton(Ruby版)

On 2010年9月14日, in Ruby, by タカ

一応、RubyでもSingleton。
Rubyは標準で実装されているから楽。


test.rb

require 'singleton'
class SingletonTest
  include Singleton
end

p SingletonTest.instance
p SingletonTest.instance

サンプル実行

$ ruby test.rb
#<SingletonTest:0xb7d579a8>
#<SingletonTest:0xb7d579a8>
Tagged with:  

Singleton(PHP版)

On 2010年9月14日, in PHP, by タカ

こちらもたまーに使うのでメモエントリー。


Singleton.class.php

<?php
class Singleton
{
    static private $instance = null;

    private function __construct()
    {
    }

    static function instance()
    {
        if (!is_null(self::$instance)) return self::$instance;
        self::$instance = new self();
        return self::$instance;
    }
}

test.php

<?php
require_once 'Singleton.class.php';

$obj1 = Singleton::instance();
$obj2 = Singleton::instance();

var_dump($obj1);
var_dump($obj2);

サンプル実行

$ php test.php
object(Singleton)#1 (0) {
}
object(Singleton)#1 (0) {
}
Tagged with:  

Singleton

On 2010年9月14日, in Objective-C, by タカ

比較的よく使うのでメモとしてエントリー


Singleton.h

#import <Foundation/Foundation.h>
@interface Singleton : NSObject {

}
+ (id)instance;

Singleton.m

@implementation Singleton

static id _instance = nil;

+ (id)instance
{
    @synchronized(self) {
        if (!_instance) {
            [[self alloc] init];
        }
    }
    return _instance;
}

+ (id)allocWithZone:(NSZone *)zone
{
    @synchronized(self) {
        if (!_instance) {
            _instance = [super allocWithZone:zone];
            return _instance;
        }
    }
    return nil;
}

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

- (id)retain
{
    return self;
}

- (unsigned)returnCount
{
    return UINT_MAX;
}

- (void)release
{
}

- (id)autorelease
{
    return self;
}

@end

クローラ

On 2010年2月14日, in 未分類, by タカ

作成中です。

Storategyパターンで使用するコマンドは切り替えられるようにする予定。

そうすると、コマンド引数によってそれぞれ条件が変わるから
そこをある程度吸収できる仕組みは必要。

Facadeパターンとかで吸収できるかなぁと思ってる。
でも、最大公約か最小公倍かで悩み中。

取り急ぎ、Webクローラを作ります。

Tagged with: