Naive implementation of decorator drawing in Objective-C

I read from Cocoa Design Patterns that decorator pattern is used in many Cocoa classes, including NSAttributedString (which does not inherit from NSString ). I looked at the implementation of NSAttributedString.m , and it was above my head, but I would be interested to know if any of the SOs successfully implemented this template And they are ready to share.

The requirements are adapted from this decorator template reference , and since there are no abstract classes in Objective-C, Component and Decorator should be similar enough for abstract classes and serve their original purpose (i.e. I do not think that they can be protocols, because you should be able to do [super operation] .

I would be very happy to see some of your decorator implementations.

+7
source share
1 answer

I used it in one of my applications where I had several cell views. I have a cell with a border and a cell that had additional buttons and a cell with a textured image. I also needed to change them with the click of a button

Here is 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 a custom cell with a 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 opinion, the controller, I will do the following

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

If later I wanted to switch to another cell, I would do

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

All Articles