Note that there are some explanatory texts on larger screens.

plurals
  1. POTrouble with Decorator pattern, iOS / UICollectionViewCells
    primarykey
    data
    text
    <p>I am trying to 'decorate' UICollectionViewCells using the Decorator pattern.</p> <p>For example, if I have a</p> <pre><code> BaseCell : UICollectionViewCell </code></pre> <p>I would like to be able to do something like this:</p> <pre><code> 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. </code></pre> <p>I think the Decorator pattern is pretty neat for this sort of thing, but I'm having difficulty applying it to collection views. </p> <p>Firstly, in UICollectionViewControllers you need to register a class, like this:</p> <pre><code> [self.collectionView registerClass:cellClass forCellWithReuseIdentifier:cellIdentifier]; </code></pre> <p>So I don't have an opportunity to make my own instance.</p> <p>Secondly, I can't see how the Decorator can ever be useful for decorating 'non-pure' objects, that is, objects that I didn't create from the ground up but have their own properties and behaviours (such as UICollectionViewCell). Since in the example above, <code>cell</code> represents a new instance of LabelledCell, and if UICollectionView makes a call on a method, eg, <code>isSelected</code>, this will call <code>aLabelledCellInstance.isSelected</code> unless I specifically do this in my Decorator base class:</p> <pre><code> - (BOOL)isSelected { return self.decoratedCell.isSelected; } </code></pre> <p>Which is fine for one method but it doesn't seem right to have to override every method in <code>UICollectionViewCell</code>. Should I be using <code>forwardInvocation:</code>? </p> <p>Am I abusing this pattern, and are there alternatives? Because it works very nicely in books when you just have to override basic methods like</p> <pre><code> getPrice() { return decoratedObject.getPrice() + 1.10f; } </code></pre> <p>.. but seems hard to fit to the purpose of actually decorating existing UI elements with custom behaviour.</p> <p>Thanks</p> <p>EDIT: What I am trying to avoid is having classes like this:</p> <ul> <li>GlowingBorderedCell</li> <li>LabelledGlowingBorderedCell</li> <li>etc.</li> </ul> <p>On paper the Decorator is the perfect candidate for what I am trying to achieve but the implementation is absolutely stumping me.</p>
    singulars
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload