繁体   English   中英

在Objective-C中实现装饰模式

[英]Naive implementation of decorator pattern in Objective-C

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

需求是根据这个装饰器模式引用而改编的,因为Objective-C中没有抽象类,所以ComponentDecorator应该足够类似于抽象类并满足它们的原始目的(即我不认为它们可以是协议,因为你必须能够[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];
}

现在在我的视图控制器中,我将执行以下操作

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

如果以后我想切换到另一个单元格我会这样做

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM