iphone - Objective-C 中的装饰器模式

标签 iphone objective-c design-patterns decorator

我正在考虑使用 decorator pattern扩展 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

总而言之,问题是被装饰对象的方法重复,即使我不需要在那里改变任何东西。有没有更简单的方法来传递那些我不需要“覆盖”的方法?我可以为此使用 NSProxy 之类的东西吗?

编辑:这对我来说主要是一个理论问题,因为我意识到装饰器模式不是我解决实际问题所需要的。但是,因为我以后可能会再次使用它,所以我仍然对您的答案很感兴趣。

最佳答案

是的,可以用 NSProxy 在 Objective-C 中实现 Decorator 模式.您将必须实现 methodSignatureForSelector: 和 forwardInvocation: 到 forward messages到装饰对象。

但我认为这不是您在这里尝试做的事情的好解决方案;发送调用非常 costly并且不是为了这样的目的 - 当然有更好的方法来实现你想做的事情,例如带有类别(或者方法调配)。

关于iphone - Objective-C 中的装饰器模式,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4312339/

相关文章:

iphone - 为几个ios版本导入 header ?

objective-c - 在 C/Objective-C 中将返回值放在括号中的目的是什么?

iphone - 在iphone sdk中将文件夹从资源复制到文档

design-patterns - 软件架构设计模式

c# - 异常处理的良好实践设计模式

java - 通过使用反射来破解类字段的任何设计模式

ios - iPhone SE 只能从 iPA 下载 2 个图标吗?

ios - AppStore iOS警告ITMS-9000 “Legacy Language Designator”

iphone - 每隔x分钟在后台检查一次条件,如果为true,则发送通知

iphone - iOS - 计算距离、方位角、仰角和相对位置(增强现实)