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

[英]How to create a strategy pattern in Objective-C?


I need to develop a strategy pattern where i have a main class with other three classes where i need to refer to the objects of the other three classes using the main class object.To solve this is the strategy pattern will help me? If so please do give me the syntax in Objective-C?

我需要開發一個策略模式,其中我有一個主類和其他三個類,我需要使用主類對象引用其他三個類的對象。要解決這個問題,策略模式會對我有幫助嗎?如果是這樣,請給我Objective-C中的語法?

2 个解决方案

#1


39  

You'll want to look at Objective-C's protocol mechanism. Here's a simple protocol with a single required method:

您將要了解Objective-C的協議機制。這是一個簡單的協議,只需一個方法:

@protocol Strategy <NSObject>

@required
- (void) execute;

@end

Then you declare a class that fulfills that protocol:

然后聲明一個滿足該協議的類:

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

The implementation must provide the -execute method (since it was declared as @required):

實現必須提供-execute方法(因為它被聲明為@required):

@implementation ConcreteStrategyA

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

@end

You can make a similar ConcreteStrategyB class, but I'm not going to show it here.

你可以制作一個類似的ConcreteStrategyB類,但我不會在這里展示它。

Finally, make a context class with a property maintaining the current strategy.

最后,創建一個具有維護當前策略的屬性的上下文類。

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

- (void) execute;

@end

Here is the implementation. The method that delegates to the strategy's -execute method just happens to be called -execute as well, but it doesn't have to be.

這是實施。委托給策略的-execute方法的方法恰好也被稱為-execute,但不一定如此。

@implementation Context

@synthesize strategy;

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

@end

Now I'll make a few instances and put them to use:

現在我將制作一些實例並將它們用於:

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

The console output shows that the strategy was successfully changed:

控制台輸出顯示策略已成功更改:

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

Note that if the protocol does not specify @required, the method is optional. In this case, the context needs to check whether the strategy implements the method:

請注意,如果協議未指定@required,則該方法是可選的。在這種情況下,上下文需要檢查策略是否實現了該方法:

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

This is a common Cocoa pattern called delegation. For more information on delegation and other design patterns in Cocoa, see this.

這是一種常見的Cocoa模式,稱為委托。有關Cocoa中的委派和其他設計模式的更多信息,請參閱此內容。

#2


1  

Here's a bit more of a concrete example. You can put each item in a separate file. I've put it all in one file for ease of understanding.

這里有一個具體的例子。您可以將每個項目放在單獨的文件中。為了便於理解,我把它全部放在一個文件中。

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

注意!

本站翻译的文章,版权归属于本站,未经许可禁止转摘,转摘请注明本文地址:https://www.itdaan.com/blog/2010/02/10/72058fe456eddf4f53cceb365215e2ce.html



 
粤ICP备14056181号  © 2014-2020 ITdaan.com