Created
October 25, 2012 09:23
-
-
Save chiahsien/3951598 to your computer and use it in GitHub Desktop.
Singleton 使用範例
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// 在玩遊戲的 View Controller | |
#import "PlayGameViewController.h" | |
#import "ScoreManager.h" | |
// 遊戲結束了,有個方法專門用來處理後續動作 | |
- (void)gameOver | |
{ | |
// 1. 取得 score manager | |
ScoreManager *scoreManager = [ScoreManager sharedInstance]; | |
// 2. 更新使用者的分數 | |
[scoreManager updateScore:forUser:]; | |
// 3. 或許你還需要一些收尾的動作 | |
........ | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// 在你的 ScoreManager.m 裡頭 | |
#import "ScoreManager.h" | |
@implementation ScoreManager | |
+ (ScoreManager *)sharedInstance | |
{ | |
static dispatch_once_t once; | |
static ScoreManager *sharedScoreManager; | |
dispatch_once(&once, ^ { sharedScoreManager = [[ScoreManager alloc] init]; }); | |
return sharedScoreManager; | |
} | |
- (NSUInteger)getScoreForUser:(NSString *)userId | |
{ | |
NSUInteger score; | |
// 取得某位使用者的分數 | |
score = .....; | |
return score; | |
} | |
- (void)updateScore:(NSUInteger)score forUser:(NSString *)userId | |
{ | |
// 在這裡更新使用者的分數 | |
........ | |
// 或許最後你會想要把分數存到資料庫 | |
[self saveScore]; | |
} | |
- (void)saveScore | |
{ | |
// 在這裡處理儲存分數的動作,看是要寫到 UserDefaults 還是寫到 SQLite,還是其他。 | |
// 獨立成一個方法,會比較好管理程式碼。 | |
} | |
@end |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// 在顯示排行榜的 View Controller | |
#import "ShowScoreViewController.h" | |
#import "ScoreManager.h" | |
// 或許你會有一個專門用來顯示某位使用者分數的方法 | |
- (void)showScoreForUser:(NSString *)userId | |
{ | |
// 1. 取得 score manager | |
ScoreManager *scoreManager = [ScoreManager sharedInstance]; | |
// 2. 取得該使用者的分數 | |
NSUInteger score = [scoreManager getScoreForUser:userId]; | |
// 3. 顯示分數 | |
..... | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment