7

Cocoa Design Patternsという本から、デコレータパターンが(から継承しない)Cocoaを含む多くのクラスで使用されていることを読みました。私は実装を調べましたが、それは私の頭の中にありましたが、SO の誰かがこのパターンを正常に実装し、喜んで共有しているかどうかを知りたいと思います。NSAttributedStringNSStringNSAttributedString.m

要件は、このデコレータ パターン リファレンスから適応されます。Objective-C には抽象クラスがないため、Componentとは、Decoratorクラスを抽象化し、元の目的を果たすのに十分に類似している必要があります (つまり、プロトコルにすることはできないと思います。なぜなら、できる必要があります[super operation]

あなたのデコレータの実装のいくつかを見て、私は本当にわくわくします。

4

1 に答える 1

3

私はセルの複数の表現を持っていたアプリの1つでそれを使用しました。境界線のあるセル、追加のボタンのあるセル、テクスチャ付きの画像のあるセルがあり、クリックするだけでそれらを変更する必要がありましたボタンの

これが私が使用したコードの一部です

//CustomCell.h
@interface CustomCell : UIView

//CustomCell.m
@implementation CustomCell

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

@end

そして、ボーダー付きのカスタムセルの場合

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

今私のView Controllerで、私は次のことをします

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

後で別のセルに切り替えたい場合は、そうします

CellWithTexture *cellWithBorder = [[CellWithTexture alloc] initWithCell:cellWithBorder.cell];
于 2012-06-08T15:12:07.220 に答える