美文网首页
模版模式学习

模版模式学习

作者: 不存在的昵称 | 来源:发表于2018-07-12 18:45 被阅读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
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];

相关文章

  • 设计模式-模版方法模式

    设计模式-模版方法模式 定义 模版方法模式(Template Method Pattern)又叫模版模式,是指定义...

  • 模版模式学习

    模版模式学习 TemplatePattern 看了YouXianMing的github感觉需要加深一下印象。今天看...

  • 设计模式[14]-模版方法模式-Template Method

    1.模版方法模式简介 模版方法模式(Template Method Pattern)是行为型(Behavioral...

  • 设计模式之模版方法模式

    模版方法模式 模版方法是一种只需使用继承就可以实现的非常简单的模式模版方法模式由两部分结构组成,第一部分是抽象父类...

  • 设计模式之模版方法模式

    模版方法模式 模版方法是一种只需使用继承就可以实现的非常简单的模式模版方法模式由两部分结构组成,第一部分是抽象父类...

  • 模版方法模式

    模版方法模式 一、什么是模版方法模式 模板模式 :解决某类事情的步骤有些是固定的,有些是会发生变化的,那么这时候我...

  • 设计模式之Template模式(模版模式)

    1 模式简介 1.1 模版方法模式的定义:模版方法模式在一个方法中定义一个算法的骨架,而将一些步骤延迟到子类中。模...

  • 模版方法模式

    通俗讲,模版模式就是将通用的上升到父类中,个性化的功能由各个子类完成.代码的复用是模版模式主要解决的.

  • 模版模式

    类图 模版模式.png 实现 调用 输出 把某东西装进冰箱的类 把大象装冰箱 把苹果装冰箱 The Templat...

  • 模版方法模式

    模版方法模式 定义:定义一个操作中算法的框架,而将一些步骤延迟到子类中,使得子类可以不改变算法的结构即可重定义该算...

网友评论

      本文标题:模版模式学习

      本文链接:https://www.haomeiwen.com/subject/phgrpftx.html