2012-06-08 26 views
7

我從書可可設計模式的裝飾圖案,在許多Cocoa類中使用,包括NSAttributedString(不從NSString繼承)讀取。我looked at an implementation NSAttributedString.m,它是在我的頭上,但我會有興趣知道SO上的任何人是否成功實施了這種模式,他們願意分享。幼稚的做法在Objective-C Decorator模式

的要求是從this decorator pattern reference適應並因爲有在Objective-C沒有抽象類中,ComponentDecorator應適當足夠的抽象類相似,並且滿足他們的初衷(即我不認爲他們可以協議,因爲你必須能夠做到[super operation]

我會很高興地看到一些你的裝飾中實現的。

回答

3

我用它在我的應用程序之一,我有一個細胞 的多重表達我有一個有邊界的單元格和一個有額外的單元格按鈕和有紋理的圖象單元 我還需要一鍵

這裏的點擊來改變他們的是一些我用

//CustomCell.h 
@interface CustomCell : UIView 

//CustomCell.m 
@implementation CustomCell 

- (void)drawRect:(CGRect)rect 
{ 
    //Draw the normal images on the cell 
} 

@end 

而對於自定義單元格邊境的代碼

//CellWithBorder.h 
@interface CellWithBorder : CustomCell 
{ 
    CustomCell *aCell; 
} 

//CellWithBorder.m 
@implementation CellWithBorder 

- (void)drawRect:(CGRect)rect 
{ 
    //Draw the border 
    //inset the rect to draw the original cell 
    CGRect insetRect = CGRectInset(rect, 10, 10); 
    [aCell drawRect:insetRect]; 
} 

現在,在我的視圖控制器,我會做以下

CustomCell *cell = [[CustomCell alloc] init]; 
CellWithBorder *cellWithBorder = [[CellWithBorder alloc] initWithCell:cell]; 

如果以後我想切換到另一個細胞我會做

CellWithTexture *cellWithBorder = [[CellWithTexture alloc] initWithCell:cellWithBorder.cell]; 
+0

@RobNapier不,這是裝飾,裝飾器是一個「子類」,即「有一個」參考超類,裝飾也必須符合超類接口 –

+0

你是對的;我誤解了代碼。 –

+0

@RobNapier :),我愛你的書btw –