裝飾器模式可以在不改變既有類別的前提下,動態為物件添加職責。它常用來取代複雜的子類化,讓功能擴充更靈活。

Category 可為既有類別新增方法,而不建立子類。例如 Album 是模型物件,但需要提供 UITableView 可用的資料結構。


- (NSDictionary *)tr_tableRepresentation {
return @{@"titles": @[@"Artist", @"Album", @"Genre", @"Year"],
@"values": @[self.artist, self.title, self.genre, self.year]};
}
這種做法不需要修改 Album 原始程式碼,也不需建立 Album 子類。Apple 在 Foundation 與 UIKit 中也大量使用 Category。
Delegation 是另一種常見的裝飾式設計。UITableView 不知道每個 section 有多少行,於是透過 delegate 向外部詢問。ViewController 可宣告遵循 UITableViewDataSource 與 UITableViewDelegate,並實作必要方法。

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
return [currentAlbumData[@"titles"] count];
}
若未實作必要方法,執行時可能出現例外。因此使用 delegate 時,必須確認所有必要方法都已提供。

