Objective C 语言 使用策略模式的策略工厂

Objective-C阿木 发布于 2025-06-29 10 次阅读


策略模式与Objective-C中的策略工厂实现

在软件开发中,策略模式是一种常用的设计模式,它允许在运行时选择算法的行为。这种模式特别适用于那些算法可以互换的场景,使得算法的变化不会影响到使用算法的客户端代码。Objective-C作为一种面向对象的编程语言,同样可以很好地应用策略模式。本文将围绕Objective-C语言,探讨策略模式的基本概念,并实现一个策略工厂,用于动态地创建和切换策略对象。

策略模式概述

策略模式定义了一系列算法,并将每一个算法封装起来,使它们可以互相替换。策略模式让算法的变化独立于使用算法的客户端。在策略模式中,通常包含以下角色:

- Context(环境类):维护一个策略对象的引用,负责发起对策略对象的调用。

- Strategy(策略接口):定义所有支持的算法的公共接口。

- ConcreteStrategy(具体策略类):实现Strategy接口,定义所有支持的算法。

策略工厂实现

1. 定义策略接口

我们需要定义一个策略接口,它将包含所有支持的算法。

objc

@protocol Strategy <NSObject>

- (void)execute;

@end


2. 实现具体策略类

接下来,我们实现几个具体的策略类,它们都遵循策略接口。

objc

@interface ConcreteStrategyA : NSObject <Strategy>

@end

@implementation ConcreteStrategyA

- (void)execute {


NSLog(@"Executing strategy A");


}

@end

@interface ConcreteStrategyB : NSObject <Strategy>

@end

@implementation ConcreteStrategyB

- (void)execute {


NSLog(@"Executing strategy B");


}

@end


3. 创建环境类

环境类负责维护一个策略对象的引用,并调用策略对象的`execute`方法。

objc

@interface Context : NSObject

@property (nonatomic, strong) id<Strategy> strategy;

- (void)setStrategy:(id<Strategy>)strategy;


- (void)executeStrategy;

@end

@implementation Context

- (void)setStrategy:(id<Strategy>)strategy {


_strategy = strategy;


}

- (void)executeStrategy {


if (_strategy) {


[_strategy execute];


}


}

@end


4. 实现策略工厂

策略工厂用于创建具体的策略对象,并返回给客户端。

objc

@interface StrategyFactory : NSObject

+ (id<Strategy>)createStrategyWithType:(NSString )type;

@end

@implementation StrategyFactory

+ (id<Strategy>)createStrategyWithType:(NSString )type {


if ([type isEqualToString:@"A"]) {


return [[ConcreteStrategyA alloc] init];


} else if ([type isEqualToString:@"B"]) {


return [[ConcreteStrategyB alloc] init];


}


return nil;


}

@end


5. 使用策略工厂

现在我们可以使用策略工厂来创建具体的策略对象,并使用环境类来执行策略。

objc

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


@autoreleasepool {


Context context = [[Context alloc] init];


id<Strategy> strategy = [StrategyFactory createStrategyWithType:@"A"];


[context setStrategy:strategy];


[context executeStrategy];



strategy = [StrategyFactory createStrategyWithType:@"B"];


[context setStrategy:strategy];


[context executeStrategy];


}


return 0;


}


总结

本文介绍了策略模式的基本概念,并在Objective-C中实现了一个策略工厂。通过策略工厂,我们可以动态地创建和切换策略对象,而不需要修改客户端代码。这种设计模式使得代码更加灵活,易于维护和扩展。

在实际项目中,策略模式可以应用于各种场景,如排序算法、加密算法、支付方式等。通过合理地应用策略模式,我们可以提高代码的可读性、可维护性和可扩展性。