Objective-C中的装饰模式

Mih*_*ian 9 iphone design-patterns objective-c decorator

我正在考虑使用装饰器模式来扩展UIKit类的功能.我面临的问题是,从我在其他语言中看到的例子中,模式迫使我复制装饰对象的界面.以下是我将如何看待实现的模式:

// Inheritance used for compile time check only
@interface UIScrollViewDecorator : UIScrollView
{
    UIScrollview *decoratedScrollView;
}

- (id)initWithScrollView:(UISCrollView*)scrollView;

@end

@implementation UIScrollViewDecorator

- (id)initWithScrollView:(UISCrollView*)scrollView
{
    self = [super init];
    if(self != nil)
    {
        decoratedScrollView = [scrollView retain];
        // maybe set up some custom controls on decoratedScrollView
    }
}

// all methods for UIScrollView need to be manually passed to the decorated object
//   -- this is the problem
- (void)scrollRectToVisible:(CGRect)rect animated:(BOOL)animated
{
    // use "overwritten methods" to mess with the input for the decorated scroll view
    // most of the time though I have no need to make any adjustments here; I still need
    // to pass all these messages through so that outside users can interact with me just
    // like with a real UIScrollView
    [decoratedScrollView scrollRectToVisible:rect animated:animated];
}

@end
Run Code Online (Sandbox Code Playgroud)

总而言之,问题是装饰对象方法的重复,即使我不需要改变任何东西.是否有更简单的方法来传递那些我不需要"覆盖"的方法?我可以使用像NSProxy这样的东西吗?

编辑:这对我来说已成为一个理论上的问题,因为我意识到装饰模式不是解决我实际问题所需要的.但是,由于我将来可能再次使用它,我仍然对你的答案非常感兴趣.

w-m*_*w-m 4

是的,可以使用 NSProxy 在 Objective-C 中实现装饰器模式。您必须实现 methodSignatureForSelector: 和forwardInspiration: 将消息转发到装饰对象。

但我不认为这对于您在这里尝试做的事情来说是一个好的解决方案;发送调用的成本非常,并且不适合这样的目的 - 当然有更好的方法来实现您想要做的事情,例如使用类别(或者可能是方法调配)。