objective-c - 如何在 Objective-C 中创建策略模式?

标签 objective-c strategy-pattern

我需要开发一个策略模式,其中我有一个主类和其他三个类,我需要使用主类对象引用其他三个类的对象。要解决这个问题,策略模式会帮助我吗?如果是这样,请给我 Objective-C 中的语法?

最佳答案

你会想看看 Objective-C 的 protocol机制。这是一个简单的协议(protocol),只有一个必需的方法:

@protocol Strategy <NSObject>

@required
- (void) execute;

@end

然后声明一个满足该协议(protocol)的类:

@interface ConcreteStrategyA : NSObject <Strategy>
{
    // ivars for A
}
@end

实现必须提供-execute方法(因为它被声明为@required):

@implementation ConcreteStrategyA

- (void) execute
{
    NSLog(@"Called ConcreteStrategyA execute method");
}

@end

您可以制作一个类似的ConcreteStrategyB 类,但我不打算在这里展示它。

最后,创建一个具有维护当前策略的属性的上下文类。

@interface Context : NSObject
{
    id<Strategy> strategy;
}
@property (assign) id<Strategy> strategy;

- (void) execute;

@end

这里是实现。委托(delegate)给策略的 -execute 方法的方法恰好也被称为 -execute,但不一定是。

@implementation Context

@synthesize strategy;

- (void) execute
{
    [strategy execute];
}

@end

现在我将创建几个实例并使用它们:

ConcreteStrategyA * concreteStrategyA = [[[ConcreteStrategyA alloc] init] autorelease];
ConcreteStrategyB * concreteStrategyB = [[[ConcreteStrategyB alloc] init] autorelease];
Context * context = [[[Context alloc] init] autorelease];

[context setStrategy:concreteStrategyA];
[context execute];
[context setStrategy:concreteStrategyB];
[context execute];    

控制台输出显示策略修改成功:

2010-02-09 19:32:56.582 Strategy[375:a0f] Called ConcreteStrategyA execute method
2010-02-09 19:32:56.584 Strategy[375:a0f] Called ConcreteStrategyB execute method

请注意,如果协议(protocol)未指定@required,则该方法是可选的。在这种情况下,上下文需要检查策略是否实现了方法:

- (void) execute
{
    if ([strategy respondsToSelector:@selector(execute)])
        [strategy execute];
}

这是一种常见的 Cocoa 模式,称为 delegation .有关 Cocoa 中委托(delegate)和其他设计模式的更多信息,see this .

关于objective-c - 如何在 Objective-C 中创建策略模式?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2234174/

相关文章:

design-patterns - 如何从策略模式的这种使用中移除循环依赖?

objective-c - 希望编写一个 4 路温度转换器 Objective-C 控制台程序

ios - 如何摆脱有关 View 相互叠加的通知?

objective-c - 有什么方法可以将 NSArray 传递给需要可变数量参数的方法,例如 +stringWithFormat :

objective-c - Xcode 4 模板在 iOS 3.1.2 中不起作用

iphone - 识别圆圈手势以删除注释,如何检测圆圈?

c++ - C++ 中的组件/策略模式、设计和实现

c# - DDD - 如何强制执行不变量但特定于客户要求?

design-patterns - Scala 中策略模式的更好替代方案?

oop - 策略模式是对的吗?