模版模式学习

2018-07-12  本文已影响0人  不存在的昵称

模版模式学习

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.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.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];
上一篇 下一篇

猜你喜欢

热点阅读