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.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) {
}
比較的よく使うのでメモとしてエントリー
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
作成中です。
Storategyパターンで使用するコマンドは切り替えられるようにする予定。
そうすると、コマンド引数によってそれぞれ条件が変わるから
そこをある程度吸収できる仕組みは必要。
Facadeパターンとかで吸収できるかなぁと思ってる。
でも、最大公約か最小公倍かで悩み中。
取り急ぎ、Webクローラを作ります。

最新コメント