我从 Cocoa Design Patterns 一书中读到装饰器模式在许多 Cocoa
类中使用,包括 NSAttributedString
(它不继承自 NSString
)。我 looked at an implementation NSAttributedString.m
这超出了我的理解范围,但我很想知道 SO 上是否有人成功实现了这种模式并且他们愿意分享。
要求改编自this decorator pattern reference并且由于在 Objective-C 中没有抽象类,Component
和 Decorator
应该足够相似以抽象类并服务于它们的原始目的(即我不认为它们可以是协议(protocol),因为您必须能够执行 [super operation]
。
如果看到您对装饰器的一些实现,我会非常激动。
最佳答案
我在我的一个应用程序中使用了它,其中我有一个单元格的多个表示 我有一个有边框的单元格,一个有额外按钮的单元格和一个有纹理图像的单元格 我还需要单击按钮来更改它们
这是我使用的一些代码
//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];
}
现在在我的 View Controller 中,我将执行以下操作
CustomCell *cell = [[CustomCell alloc] init];
CellWithBorder *cellWithBorder = [[CellWithBorder alloc] initWithCell:cell];
如果稍后我想切换到另一个单元格,我会这样做
CellWithTexture *cellWithBorder = [[CellWithTexture alloc] initWithCell:cellWithBorder.cell];
关于objective-c - Objective-C 装饰器模式的简单实现,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10951080/