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

时间:2010-02-10 03:12:15

标签: objective-c strategy-pattern

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

2 个答案:

答案 0 :(得分:39)

您需要查看Objective-C的protocol机制。这是一个简单的协议,只需一个方法:

@protocol Strategy <NSObject>

@required
- (void) execute;

@end

然后声明一个符合该协议的类:

@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

这是实施。委托给策略的-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

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

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

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

答案 1 :(得分:1)

这里有一个具体的例子。您可以将每个项目放在单独的文件中。为了便于理解,我把它全部放在一个文件中。

//  main.m
//  StrategyWikipediaExample
//
//  Created by steve on 2014-07-08.
//  Copyright (c) 2014 steve. All rights reserved.
//

#import <Foundation/Foundation.h>

/**
 Equivalent to Java Interface
 All concrete Strategies conform to this protocol
 */
@protocol MathOperationsStrategy<NSObject>
- (void)performAlgorithmWithFirstNumber:(NSInteger)first secondNumber:(NSInteger)second;
@end

/**
 Concrete Strategies. 
 Java would say they "Extend" the interface.
 */

@interface AddStrategy : NSObject<MathOperationsStrategy>
@end
@implementation AddStrategy
- (void)performAlgorithmWithFirstNumber:(NSInteger)first secondNumber:(NSInteger)second
{
    NSInteger result = first + second;
    NSLog(@"Adding firstNumber: %ld with secondNumber: %ld yields : %ld", first, second, result);
}
@end

@interface SubtractStrategy : NSObject<MathOperationsStrategy>
@end
@implementation SubtractStrategy
- (void)performAlgorithmWithFirstNumber:(NSInteger)first secondNumber:(NSInteger)second
{
    NSInteger result = first - second;
    NSLog(@"Subtracting firstNumer: %ld with secondNumber: %ld yields: %ld", first, second, result);
}
@end

@interface MultiplyStrategy : NSObject<MathOperationsStrategy>
@end
@implementation MultiplyStrategy
- (void)performAlgorithmWithFirstNumber:(NSInteger)first secondNumber:(NSInteger)second
{
    NSInteger result = first * second;
    NSLog(@"Multiplying firstNumber: %ld with secondNumber: %ld yields: %ld", first, second, result);
}
@end

@interface Context : NSObject
@property (weak, nonatomic)id<MathOperationsStrategy>strategy; // reference to concrete strategy via protocol
- (id)initWithMathOperationStrategy:(id<MathOperationsStrategy>)strategy; // setter
- (void)executeWithFirstNumber:(NSInteger)first secondNumber:(NSInteger)second;
@end
@implementation Context
- (id)initWithMathOperationStrategy:(id<MathOperationsStrategy>)strategy
{
    if (self = [super init]) {
        _strategy = strategy;
    }
    return self;
}
- (void)executeWithFirstNumber:(NSInteger)first secondNumber:(NSInteger)second
{
    [self.strategy performAlgorithmWithFirstNumber:first secondNumber:second];
}
@end


int main(int argc, const char * argv[])
{

    @autoreleasepool {
        id<MathOperationsStrategy>addStrategy = [AddStrategy new];
        Context *contextWithAdd = [[Context alloc] initWithMathOperationStrategy:addStrategy];
        [contextWithAdd executeWithFirstNumber:10 secondNumber:10];

    }
    return 0;
}