tac*_*cos 7 oop design-patterns objective-c decorator ios
我从" 可可设计模式 "一书中读到,装饰器模式在许多Cocoa类中都有使用,包括NSAttributedString(不继承NSString).我查看了一个实现NSAttributedString.m,它已经超出了我的想象,但我很想知道SO上是否有人成功实现了这种模式并且他们愿意分享.
这些需求是根据这个装饰器模式引用而改编的,因为Objective-C中没有抽象类,所以Component它Decorator应该与抽象类足够相似并且能够满足它们的原始目的(即我不认为它们可以是协议,因为你必须能够做到[super operation].
看到你的装饰器的一些实现,我会非常激动.
我在我的一个应用程序中使用了它,其中我有一个单元格的多个表示,我有一个具有边框的单元格,一个具有附加按钮的单元格和一个具有纹理图像的单元格,我还需要通过单击来更改它们一个按钮的
这是我使用的一些代码
//CustomCell.h
@interface CustomCell : UIView
//CustomCell.m
@implementation CustomCell
- (void)drawRect:(CGRect)rect
{
//Draw the normal images on the cell
}
@end
Run Code Online (Sandbox Code Playgroud)
对于带边框的自定义单元格
//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];
}
Run Code Online (Sandbox Code Playgroud)
现在在我的视图控制器中,我会执行以下操作
CustomCell *cell = [[CustomCell alloc] init];
CellWithBorder *cellWithBorder = [[CellWithBorder alloc] initWithCell:cell];
Run Code Online (Sandbox Code Playgroud)
如果稍后我想切换到另一个单元格我会这样做
CellWithTexture *cellWithBorder = [[CellWithTexture alloc] initWithCell:cellWithBorder.cell];
Run Code Online (Sandbox Code Playgroud)