設計模式與架構

何為架構?

架構(Architecture)
軟件開發中的設計方案
類與類之間的關系、模塊與模塊之間的關系、客戶端與服務端的關系

經常聽到的架構名詞
MVC、MVP、MVVM、VIPER、CDD
三層架構、四層架構
......

傳統的MVC模式

Traditional MVC

蘋果的 MVC

蘋果官網地址

[Cocoa MVC]

示例:
Model

@interface ShopModel : NSObject
@property (copy, nonatomic) NSString *title;
@property (copy, nonatomic) NSString *price;
@end

@implementation ShopModel
@end

DataSource

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    static  NSString *ID = @"CellID";
    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:ID];
    if (!cell) {
        cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:ID];
    }
    ShopModel *shop = self.shopData[indexPath.row];
***************************************
cell和model之間并沒有直接關系
***************************************
    cell.detailTextLabel.text = shop.price;
    cell.textLabel.text = shop.title;
    return cell;
}

優點:View、Model可以重復利用,可以獨立使用
缺點:Controller的代碼過于臃腫

MVC – 變種


示例:
Model

@interface TestModel : NSObject
@property (copy, nonatomic) NSString *title;
@property (copy, nonatomic) NSString *imageName;
@end

@implementation TestModel
@end

View

@class TestModel;
@interface TestView : UIView
@property (strong, nonatomic) TestModel * model;
@end

@implementation TestView

- (instancetype)initWithFrame:(CGRect)frame
{
    if (self = [super initWithFrame:frame]) {
        .....
    }
    return self;
}

- (void)setModel:(TestModel *)model{
    _model = model;
    self.iconView.image = [UIImage imageNamed:model.imageName];
    self.nameLabel.text = model.title;
}

@end

VC


- (void)viewDidLoad {
    [super viewDidLoad];
    TestModel *model = [[TestModel alloc] init];
    model.title = @"QQ";
    model.imageName = @"QQ";
    TestView *testView = [[TestView alloc] init];
    testView.model = model;
}

優點:對Controller進行瘦身,將View內部的細節封裝起來了,外界不知道View內部的具體實現
缺點:View依賴于Model

MVP

Passive View variant of MVP

示例:
View

@interface TestView : UIView
- (void)setTitle:(NSString *)title andImageName:(NSString *)imageName;
@end

@implementation TestView
- (void)setTitle:(NSString *)title andImageName:(NSString *)imageName
{
    _iconView.image = [UIImage imageNamed:image];
    _nameLabel.text = title;
}
@end

VC

@interface ViewController ()
@property (strong, nonatomic) TestPresenter *presenter;
@end

@implementation ViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    self.presenter = [[TestPresenter alloc] initWithController:self];
}

@end

presenter

@interface TestPresenter : NSObject
- (instancetype)initWithController:(UIViewController *)controller;
@end

@implementation TestPresenter

- (instancetype)initWithController:(UIViewController *)controller
{
    if (self = [super init]) {
        self.controller = controller;
        
        // 創建View
        TestView *testView = [[TestView alloc] init];
        testView.frame = CGRectMake(100, 100, 100, 150);
        [controller.view addSubview:testView];
        
         // 加載模型數據
         TestModel *model = [[TestModel alloc] init];
         model.title = @"QQ";
         model.imageName = @"QQ";
        // 賦值數據
        [testView setName:model.title andImage:model.imageName];
    }
    return self;
}
@end

可以看到跟蘋果的Apple’s MVC 很相似,多了一個 Presenter 模塊,取代了Controller中轉粘合劑的位置。Presenter本身與當前的ViewController中的生命周期并無關聯,作為業務處理層,個人覺得稱MVCP更合適

MVVM

MVVM

示例:
View

@class TestViewModel;
@interface TestView : UIView
@property (weak, nonatomic) TestViewModel *viewModel;
@end

@implementation TestView

- (instancetype)initWithFrame:(CGRect)frame
{
    if (self = [super initWithFrame:frame]) {
        ....
    }
    return self;
}

- (void)setViewModel:(TestViewModel *)viewModel
{
    _viewModel = viewModel;
    __weak typeof(self) waekSelf = self;
    [self.KVOController observe:viewModel keyPath:@"title" options:NSKeyValueObservingOptionNew block:^(id  _Nullable observer, id  _Nonnull object, NSDictionary<NSKeyValueChangeKey,id> * _Nonnull change) {
        waekSelf.nameLabel.text = change[NSKeyValueChangeNewKey];
    }];
    [self.KVOController observe:viewModel keyPath:@"imageName" options:NSKeyValueObservingOptionNew block:^(id  _Nullable observer, id  _Nonnull object, NSDictionary<NSKeyValueChangeKey,id> * _Nonnull change) {
        waekSelf.iconView.image = [UIImage imageNamed:change[NSKeyValueChangeNewKey]];
    }];
}

VC

@interface ViewController ()
@property (strong, nonatomic) TestViewModel *viewModel;
@end

@implementation ViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    self.viewModel = [[TestViewModel alloc] initWithController:self];
}
@end

ViewModel

@interface TestViewModel : NSObject
- (instancetype)initWithController:(UIViewController *)controller;
@end

@interface TestViewModel() <TestViewDelegate>
@property (copy, nonatomic) NSString *title;
@property (copy, nonatomic) NSString *imageName;
@end

@implementation TestViewModel

- (instancetype)initWithController:(UIViewController *)controller
{
    if (self = [super init]) {
        // 創建View
        TestView *testView = [[TestView alloc] init];
        testView.frame = CGRectMake(100, 100, 100, 150);
        testView.viewModel = self;
        [controller.view addSubview:testView];
        // 加載模型數據
        TestModel *model = [[TestModel alloc] init];
         model.title = @"QQ";
         model.imageName = @"QQ";
        
        // 設置數據
        self.title = model.title;
        self.imageName = model.imageName;
    }
    return self;
}

在MVP的基礎上,將P改成與V雙向綁定的VM就變成了MVVM,個人覺得稱為MVCVM更合適 View <-> C <-> ViewModel <-> Model
KVO監聽屬性是用的Facebook的開源框架 KVOController https://github.com/facebookarchive/KVOController

三層架構、四層架構


示例
Data

@interface HTTPTool : NSObject
+ (void)GET:(NSString *)URL params:(NSDictionary *)params success:(void (^)(id result))success failure:(void (^)(NSError *error))failure;
@end

@implementation HTTPTool
+ (void)GET:(NSString *)URL params:(NSDictionary *)params success:(void (^)(id))success failure:(void (^)(NSError *))failure{
    // 調用AFN
}
@end
@interface DBTool : NSObject
@end
@implementation DBTool
@end
Service
@interface Service : NSObject
+ (void)loadData:(NSDictionary *)params success:(void (^)(NSArray *newsData))success failure:(void (^)(NSError *error))failure;
@end

@implementation Service

+ (void)loadData:(NSDictionary *)params success:(void (^)(NSArray *newsData))success failure:(void (^)(NSError *error))failure;
{
    // 先取出本地數據
//    [DBTool loadLocalData....];
    // 如果沒有本地數據,就加載網絡數據
//    [HTTPTool GET:@"xxxx" params:nil success:^(id result) {
//        success(array);
//    } failure:failure];
}
@end

設計模式

設計模式(Design Pattern)
是一套被反復使用、代碼設計經驗的總結
使用設計模式的好處是:可重用代碼、讓代碼更容易被他人理解、保證代碼可靠性
一般與編程語言無關,是一套比較成熟的編程思想

設計模式可以分為三大類

  • 創建型模式:對象實例化的模式,用于解耦對象的實例化過程
    單例模式、工廠方法模式,等等

  • 結構型模式:把類或對象結合在一起形成一個更大的結構
    代理模式、適配器模式、組合模式、裝飾模式,等等

  • 行為型模式:類或對象之間如何交互,及劃分責任和算法
    觀察者模式、命令模式、責任鏈模式,等等

?著作權歸作者所有,轉載或內容合作請聯系作者
平臺聲明:文章內容(如有圖片或視頻亦包括在內)由作者上傳并發布,文章內容僅代表作者本人觀點,簡書系信息發布平臺,僅提供信息存儲服務。
  • 序言:七十年代末,一起剝皮案震驚了整個濱河市,隨后出現的幾起案子,更是在濱河造成了極大的恐慌,老刑警劉巖,帶你破解...
    沈念sama閱讀 228,197評論 6 531
  • 序言:濱河連續發生了三起死亡事件,死亡現場離奇詭異,居然都是意外死亡,警方通過查閱死者的電腦和手機,發現死者居然都...
    沈念sama閱讀 98,415評論 3 415
  • 文/潘曉璐 我一進店門,熙熙樓的掌柜王于貴愁眉苦臉地迎上來,“玉大人,你說我怎么就攤上這事。” “怎么了?”我有些...
    開封第一講書人閱讀 176,104評論 0 373
  • 文/不壞的土叔 我叫張陵,是天一觀的道長。 經常有香客問我,道長,這世上最難降的妖魔是什么? 我笑而不...
    開封第一講書人閱讀 62,884評論 1 309
  • 正文 為了忘掉前任,我火速辦了婚禮,結果婚禮上,老公的妹妹穿的比我還像新娘。我一直安慰自己,他們只是感情好,可當我...
    茶點故事閱讀 71,647評論 6 408
  • 文/花漫 我一把揭開白布。 她就那樣靜靜地躺著,像睡著了一般。 火紅的嫁衣襯著肌膚如雪。 梳的紋絲不亂的頭發上,一...
    開封第一講書人閱讀 55,130評論 1 323
  • 那天,我揣著相機與錄音,去河邊找鬼。 笑死,一個胖子當著我的面吹牛,可吹牛的內容都是我干的。 我是一名探鬼主播,決...
    沈念sama閱讀 43,208評論 3 441
  • 文/蒼蘭香墨 我猛地睜開眼,長吁一口氣:“原來是場噩夢啊……” “哼!你這毒婦竟也來了?” 一聲冷哼從身側響起,我...
    開封第一講書人閱讀 42,366評論 0 288
  • 序言:老撾萬榮一對情侶失蹤,失蹤者是張志新(化名)和其女友劉穎,沒想到半個月后,有當地人在樹林里發現了一具尸體,經...
    沈念sama閱讀 48,887評論 1 334
  • 正文 獨居荒郊野嶺守林人離奇死亡,尸身上長有42處帶血的膿包…… 初始之章·張勛 以下內容為張勛視角 年9月15日...
    茶點故事閱讀 40,737評論 3 354
  • 正文 我和宋清朗相戀三年,在試婚紗的時候發現自己被綠了。 大學時的朋友給我發了我未婚夫和他白月光在一起吃飯的照片。...
    茶點故事閱讀 42,939評論 1 369
  • 序言:一個原本活蹦亂跳的男人離奇死亡,死狀恐怖,靈堂內的尸體忽然破棺而出,到底是詐尸還是另有隱情,我是刑警寧澤,帶...
    沈念sama閱讀 38,478評論 5 358
  • 正文 年R本政府宣布,位于F島的核電站,受9級特大地震影響,放射性物質發生泄漏。R本人自食惡果不足惜,卻給世界環境...
    茶點故事閱讀 44,174評論 3 347
  • 文/蒙蒙 一、第九天 我趴在偏房一處隱蔽的房頂上張望。 院中可真熱鬧,春花似錦、人聲如沸。這莊子的主人今日做“春日...
    開封第一講書人閱讀 34,586評論 0 26
  • 文/蒼蘭香墨 我抬頭看了看天上的太陽。三九已至,卻和暖如春,著一層夾襖步出監牢的瞬間,已是汗流浹背。 一陣腳步聲響...
    開封第一講書人閱讀 35,827評論 1 283
  • 我被黑心中介騙來泰國打工, 沒想到剛下飛機就差點兒被人妖公主榨干…… 1. 我叫王不留,地道東北人。 一個月前我還...
    沈念sama閱讀 51,608評論 3 390
  • 正文 我出身青樓,卻偏偏與公主長得像,于是被迫代替她去往敵國和親。 傳聞我的和親對象是個殘疾皇子,可洞房花燭夜當晚...
    茶點故事閱讀 47,914評論 2 372