您现在的位置: IOS教程網 >> IOS系統 >  >> iOS 使用技巧 >> iOS 技巧大全

Objective-C 裝飾模式:概念解析與 Category 實踐

編輯:iOS 技巧大全

裝飾模式的核心思想,是在不改變原類文件、也不使用繼承的前提下,動態地擴展一個對象的功能。它的做法是創建一個包裝對象(也就是裝飾者),用它來包裹真實的對象。

場景引入

舉個例子:假設有一個 GamePad 類,現在想為它增加一個作弊功能(例如 100 條命)。如果直接在 GamePad 類裡添加,可能會影響其他子類的使用。此時我們可以採用裝飾模式的思維:先建立一個裝飾器實現 GamePad 的所有功能,再在裝飾器的子類中添加作弊方法。

GamePad 類

#import <Foundation/Foundation.h> @interface GamePad : NSObject - (void)up; - (void)down; - (void)left; - (void)right; - (void)buttonA; - (void)buttonB; @end

裝飾器類

我們創建一個裝飾器類,讓它持有一個 GamePad 實例並實現相同的方法接口。

GamePadDecorator.h:

#import <Foundation/Foundation.h> #import "GamePad.h" @interface GamePadDecorator : NSObject - (void)up; - (void)down; - (void)left; - (void)right; - (void)buttonA; - (void)buttonB; @end

GamePadDecorator.m:

#import "GamePadDecorator.h" @interface GamePadDecorator () @property (nonatomic, strong) GamePad *gamePad; @end @implementation GamePadDecorator - (instancetype)init { self = [super init]; if (self) { self.gamePad = [[GamePad alloc] init]; } return self; } - (void)up { [self.gamePad up]; } - (void)down { [self.gamePad down]; } - (void)left { [self.gamePad left]; } - (void)right { [self.gamePad right]; } - (void)buttonA { [self.gamePad buttonA]; } - (void)buttonB { [self.gamePad buttonB]; } @end

新增作弊子類

CheatGamePadDecorator.h:

#import "GamePadDecorator.h" @interface CheatGamePadDecorator : GamePadDecorator - (void)cheat; @end

CheatGamePadDecorator.m:

#import "CheatGamePadDecorator.h" @implementation CheatGamePadDecorator - (void)cheat { NSLog(@"cheat"); } @end

這樣我們就能在 Controller 中直接用 CheatGamePadDecorator 實現 GamePad 的所有功能,還能額外調用作弊方法:

#import "ViewController.h" #import "CheatGamePadDecorator.h" @implementation ViewController - (void)viewDidLoad { [super viewDidLoad]; CheatGamePadDecorator *cheaterGamePad = [[CheatGamePadDecorator alloc] init]; [cheaterGamePad up]; [cheaterGamePad down]; [cheaterGamePad cheat]; }

Cocoa Touch 中的 Category

其實 Cocoa Touch 自帶的 Category 也是對裝飾模式的一種實現。我們用 Category 來為 GamePad 添加作弊功能:

GamePad+Cheat.h:

#import "GamePad.h" @interface GamePad (Cheat) - (void)cheat; @end

GamePad+Cheat.m:

#import "GamePad+Cheat.h" @implementation GamePad (Cheat) - (void)cheat { NSLog(@"cheat"); } @end

使用方式:

#import "ViewController.h" #import "GamePad+Cheat.h" @implementation ViewController - (void)viewDidLoad { [super viewDidLoad]; GamePad *gamePad = [[GamePad alloc] init]; [gamePad up]; [gamePad down]; [gamePad cheat]; }

重要提醒

使用 Category 更為簡單,但有個細節一定要注意:盡量不要在 Category 中去重寫基類方法。 假如我們在 GamePad+Cheat 中重寫了 - (void)up 方法,那麼整個工程中的 up 方法都會被重載。即使你在任何地方都沒有引用 GamePad+Cheat.h,只要這個文件存在於工程裡,GamePad 的方法就會被重載,這往往會引發難以排查的問題。

  1. 上一篇文章:
  2. 下一篇文章:
蘋果刷機越獄教程| IOS教程問題解答| IOS技巧綜合| IOS7技巧| IOS8教程
Copyright © IOS教程網 All Rights Reserved