Naive implementation of decorator pattern in Objective

I have read from the book Cocoa Design Patterns that the decorator pattern is used in many Cocoa classes, including NSAttributedString (which does not inherit from NSString ). I looked at an implementation NSAttributedString.m and it was over my head, but I would be interested to know if anyone on SO has successfully implemented this pattern AND they are willing to share.

The requirements are adapted from this decorator pattern reference and since there are no abstract classes in Objective-C, the Component and Decorator should be suitably similar enough to abstract classes and serve their original purpose (ie I don't think they can be protocols, because you have to be able to do [super operation] .

I would be really thrilled to see some of your implementations of decorator.


I used it in one of my app where i had multiple representation of a cell i have a cell that had a border, and a cell that had had additional buttons and a cell that had a textured image I also needed to change them at a click of a button

Here is some of the code i used

//CustomCell.h
@interface CustomCell : UIView

//CustomCell.m
@implementation CustomCell

- (void)drawRect:(CGRect)rect
{
    //Draw the normal images on the cell
}

@end

And for Custom Cell With Border

//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];
}

Now in my view controller, i would do the following

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

If later on i wanted to switch to another cell i would do

CellWithTexture *cellWithBorder = [[CellWithTexture alloc] initWithCell:cellWithBorder.cell];
链接地址: http://www.djcxy.com/p/10854.html

上一篇: 调试Ruby段错误

下一篇: 天真实现Objective中的装饰器模式