在Objective-C中实现装饰模式

时间:2012-06-08 14:46:24

标签: objective-c ios oop design-patterns decorator

我从 Cocoa设计模式一书中读到,装饰器模式在许多Cocoa类中使用,包括NSAttributedString(不继承自NSString })。我looked at an implementation NSAttributedString.m这是我的头脑,但我很想知道SO上是否有人成功实施了这种模式而他们愿意分享。

要求改编自this decorator pattern reference,由于Objective-C中没有抽象类,ComponentDecorator应该足够相似,足以抽象类并满足其原始目的(即我不认为它们可以是协议,因为你必须能够[super operation]

看到你的一些装饰器实现,我真的很激动。

1 个答案:

答案 0 :(得分: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];
相关问题