模版模式学习

模版模式学习

TemplatePattern

看了YouXianMing的github感觉需要加深一下印象。
今天看了模版模式的demo,查了一些资料,发现之前在做优惠券的时候,部分手法很类似。这说明我当时的想法一定程度上是正确的。
模版模式是由抽象父类定义子类的一些行为(公开方法)。子类按照需求具体去实现。
但是YouXianMing的demo中是由一个协议定义了一些方法,由遵守该协议的类去实现这些方法
不好说两种方法孰优孰劣,目前看来都一样。


  • 基础协议 -- 模版
@protocol GameProtocol <NSObject>

@required

/**
 *  设置玩家个数
 *
 *  @param count 数目
 */
- (void)setPlayerCount:(int)count;

/**
 *  返回玩家数目
 *
 *  @return 玩家数目
 */
- (int)playerCount;

/**
 *  初始化游戏
 */
- (void)initializeGame;

/**
 *  开始游戏
 */
- (void)makePlay;

/**
 *  结束游戏
 */
- (void)endOfGame;

@end
  • 遵守协议的子类Monopoly
Monopoly.h
@interface Monopoly : NSObject <GameProtocol>

@end
Monopoly.m
@interface Monopoly ()

@property (nonatomic, assign) int gamePlayerCount;

@end

@implementation Monopoly

- (void)setPlayerCount:(int)count {
    self.gamePlayerCount = count;
}

- (int)playerCount {
    return self.gamePlayerCount;
}

- (void)initializeGame {
    NSLog(@"Monopoly initialize");
}

- (void)makePlay {
    NSLog(@"Monopoly makePlay");
}

- (void)endOfGame {
    NSLog(@"Monopoly endOfGame");
}

@end
  • 遵守协议的子类 - Chess
Chess.h
@interface Chess : NSObject <GameProtocol>

@end
Chess.m
@interface Chess ()

@property (nonatomic, assign) int gamePlayerCount;

@end

@implementation Chess

- (void)setPlayerCount:(int)count {
    self.gamePlayerCount = count;
}

- (int)playerCount {
    return self.gamePlayerCount;
}

- (void)initializeGame {
    NSLog(@"Chess initialize");
}

- (void)makePlay {
    NSLog(@"Chess makePlay");
}

- (void)endOfGame {
    NSLog(@"Chess endOfGame");
}

@end
  • 外界使用
    // chess game
    id <GameProtocol> chess = [[Chess alloc] init];
    chess.playerCount       = 2;
    [chess initializeGame];
    [chess makePlay];
    [chess endOfGame];
    
    // monopoly game
    id <GameProtocol> monopoly = [[Monopoly alloc] init];
    monopoly.playerCount       = 4;
    [monopoly initializeGame];
    [monopoly makePlay];
    [monopoly endOfGame];
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。