I am trying to "decorate" UICollectionViewCells using the Decorator template.
For example, if I have
BaseCell : UICollectionViewCell
I would like to do something like this:
BaseCell *cell = [[BaseCell alloc] initWithFrame] cell = [[GlowingCell alloc] initWithCell:cell]; cell = [[BorderedCell alloc] initWithCell:cell]; cell = [[LabelledCell alloc] initWithCell:cell]; // cell is now a glowing, bordered, labelled cell.
I think the Decorator pattern is pretty neat for this kind of thing, but it's hard for me to apply it to collectibles.
First, in UICollectionViewControllers you need to register a class, for example:
[self.collectionView registerClass:cellClass forCellWithReuseIdentifier:cellIdentifier];
Therefore, I have no way to create my own instance.
Secondly, I do not see how Decorator can ever be useful for decorating "unclean" objects, that is, objects that I did not create from scratch, but have their own properties and behavior (for example, UICollectionViewCell). Since in the above example, cell represents a new instance of LabelledCell, and if the UICollectionView makes a method call, for example isSelected , it will call aLabelledCellInstance.isSelected , unless I specifically do this in the Decorator base class:
- (BOOL)isSelected { return self.decoratedCell.isSelected; }
This is good for a single method, but does not seem to have the right to override each method in a UICollectionViewCell . Should I use forwardInvocation: :?
I am abusing this template, and are there any alternatives? Because it works very well in books when you just need to override basic methods, for example
getPrice() { return decoratedObject.getPrice() + 1.10f; }
.. but it seems difficult to actually fit into existing UI elements with user behavior.
thanks
EDIT: I try to avoid such classes:
- GlowingBorderedCell
- LabelledGlowingBorderedCell
- and etc.
On paper, Decorator is the perfect candidate for what I'm trying to achieve, but the implementation completely surpassed me.