7

我从Cocoa Design Patterns一书中读到,装饰器模式用于许多Cocoa类,包括NSAttributedString(不继承自NSString)。我查看了一个实现NSAttributedString.m,它超出了我的想象,但我很想知道 SO 上的任何人是否已经成功实现了这个模式并且他们愿意分享。

要求改编自此装饰器模式参考,并且由于在 Objective-C 中没有抽象类,Component并且Decorator应该与抽象类足够相似并服务于它们的原始目的(即我不认为它们可以是协议,因为你必须能够做到[super operation]

我会很高兴看到你的一些装饰器实现。

4

1 回答 1

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];
于 2012-06-08T15:12:07.220 回答