objective-c - Objective-C 装饰器模式的简单实现

标签 objective-c ios oop design-patterns decorator

我从 Cocoa Design Patterns 一书中读到装饰器模式在许多 Cocoa 类中使用,包括 NSAttributedString(它不继承自 NSString)。我 looked at an implementation NSAttributedString.m这超出了我的理解范围,但我很想知道 SO 上是否有人成功实现了这种模式并且他们愿意分享。

要求改编自this decorator pattern reference并且由于在 Objective-C 中没有抽象类,ComponentDecorator 应该足够相似以抽象类并服务于它们的原始目的(即我不认为它们可以是协议(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/

相关文章:

ios - CABasicAnimation从当前图层位置开始

objective-c - NSManagedObject 故障

iphone - 如何将 iPhone 摇动手势检测限制在特定情况下?

python - 如何将 "x += 5"(x 为自定义类)添加到 x 的属性中?

java - 不继承可以实现多态吗?

ios - 使用 Realm 查询返回唯一/不同的值

ios - 如何获取应用安装的用户信息

iphone - 动画自定义 UIView

ios - fabric beta 测试用户数

php - PHP 并行计算的数据库架构最佳实践?