LoginSignup
2
1

More than 5 years have passed since last update.

Objective-C での Template Method パターンって

Last updated at Posted at 2015-06-03

なんかデリゲートとか色々なやり方が見つかるのだけれども、これじゃダメなのだろうか

#import <Foundation/Foundation.h>

/// ベースクラスの抽象メソッド
@protocol AllAbstractMethodsImplemented <NSObject>
- (void)method1;
- (void)method2;
@end

/// ベースクラス
@interface AbstractClass : NSObject {
    /// 具象サブクラスのインスタンスへの弱参照を保持
    __weak AbstractClass<AllAbstractMethodsImplemented> *_concreteInstance;
}
/// @param concreteInstance 具象サブクラスのインスタンス(サブクラスにおけるself)
- (AbstractClass *)initWithConcreteInstance:(AbstractClass *)concreteInstance;
- (void)templateMethod;
@end
@implementation AbstractClass
- (AbstractClass *)initWithConcreteInstance:(AbstractClass<AllAbstractMethodsImplemented> *)concreteInstance
{
    if(self = [super init]) {
        _concreteInstance = concreteInstance;
        // initializes...
    }
    return self;
}
- (void)templateMethod
{
    // イニシャライザで渡してもらった具象サブクラスのメソッドを呼ぶ
    [_concreteInstance method1];
    [_concreteInstance method2];
}
@end

/// 具象サブクラス。AllAbstractMethodsImplemented のメソッドをすべて実装
@interface ConcreteClass : AbstractClass<AllAbstractMethodsImplemented>
- (ConcreteClass *)init;
- (void)method1;
- (void)method2;
@end
@implementation ConcreteClass
- (ConcreteClass *)init
{
    self = [super initWithConcreteInstance:self];
    if(self) {
        // initializes...
    }
    return self;
}
- (void)method1
{
    NSLog(@"method1\n");
}
- (void)method2
{
    NSLog(@"method2\n");
}
@end

/// 動作確認
int main(int argc, const char * argv[]) {
    @autoreleasepool {
        AbstractClass<AllAbstractMethodsImplemented> *object = [[ConcreteClass alloc] init];
        [object templateMethod];    // method1<改行>method2<改行>
    }
    return 0;
}
2
1
3

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
2
1