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 (i.e. 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];
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With