IOS之Objective-C学习 策略模式
Posted
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了IOS之Objective-C学习 策略模式相关的知识,希望对你有一定的参考价值。
对于策略模式,我个人理解策略模式就是对各种规则的一种封装的方法,而不仅仅是对算法的封装与调用而已。与工厂模式中简单工厂有点类似,但是比简单工厂更有耦合度,因为策略模式以相同的方法调用所有的规则,减少了规则类和规则类之间的耦合度。
接下来我用策略模式编辑代码来计算斗地主中地主根据坐庄成功失败翻倍情况的得分情况。
创建一个分数类
Score.h
#import <Foundation/Foundation.h>
#define BASIC_POINT 10
@interface Score : NSObject
@property(nonatomic,assign)double Score;
-(double)getScore;
@end
Score.m
#import "Score.h"
@implementation Score
-(instancetype)init{
self=[super init];
if (self) {
self.Score=BASIC_POINT;
}
return self;
}
-(double)getScore{
return NO;
}
@end
winScore.h
#import "Score.h"
@interface winScore : Score
@end
winScore.m
#import "winScore.h"
@implementation winScore
/*
*胜利得分
*/
-(double)getScore{
return self.Score;
}
@end
loseScore.h
#import "Score.h"
@interface loseScore : Score
@end
loseScore.m
#import "loseScore.h"
@implementation loseScore
/*
*失败得分
*/
-(double)getScore{
return self.Score*-1;
}
@end
BombScore.h
#import "Score.h"
@interface BombScore : Score
@property(nonatomic,assign)int bombCount;
-(instancetype)initWithbombCount:(int)counts;
@end
BombScore.m
#import "BombScore.h"
@implementation BombScore
/*
*翻倍得分
*/
-(instancetype)initWithbombCount:(int)bombCount{
self=[super init];
if (self) {
_bombCount=bombCount;
}
return self;
}
-(double)getScore{
double d=self.bombCount+1;
return d*self.Score;
}
@end
ScoreResult.h
#import <Foundation/Foundation.h>
#import "Score.h"
#import "loseScore.h"
#import "winScore.h"
#import "BombScore.h"
@interface ScoreResult : NSObject
@property(nonatomic,strong) Score* score;
-(instancetype)initWithSituation:(NSString *)str;
@end
ScoreResult.m
#import "ScoreResult.h"
@implementation ScoreResult
-(instancetype)initWithSituation:(NSString *)str{
self=[super init];
if (self) {
[self settleScore:str];
}
return self;
}
-(void)settleScore:(NSString *)param{
if ([param isEqualToString:@"成功"]) {
self.score=[[winScore alloc]init];
}
else if([param isEqualToString:@"翻倍"]){
self.score=[[BombScore alloc]initWithbombCount:1];//炸弹数暂时设为1
}
else{
self.score=[[loseScore alloc]init];
}
}
@end
执行代码:
#import "ViewController.h"
#import "ScoreResult.h"
@interface ViewController ()
@end
@implementation ViewController
- (void)viewDidLoad {
[super viewDidLoad];
ScoreResult *sr1=[[ScoreResult alloc]initWithSituation:@"翻倍"];
double score1= [sr1.score getScore];
NSLog(@"score1=%f",score1);
ScoreResult *sr2=[[ScoreResult alloc]initWithSituation:@"成功"];
double score2= [sr2.score getScore];
NSLog(@"score2=%f",score2);
ScoreResult *sr3=[[ScoreResult alloc]initWithSituation:@"失败"];
double score3= [sr3.score getScore];
NSLog(@"score3=%f",score3);
}
- (void)didReceiveMemoryWarning {
[super didReceiveMemoryWarning];
}
@end
运行结果:
score1=20.000000
score2=10.000000
score3=-10.000000
对策略模式做一个总结,策略模式是将一些规律封装策略的context类中,然后通过调用策略context类中的方法就可以得出想要的结果。上述代码中ScoreResult类就是策略的Context类。
以上是关于IOS之Objective-C学习 策略模式的主要内容,如果未能解决你的问题,请参考以下文章
《iOS开发全然上手——使用iOS 7和Xcode 5开发移动与平板应用》之Objective-C新手训练营