如何在 Objective-C 中创建策略模式?
我需要开发一种策略模式,其中我有一个主类和其他三个类,我需要使用主类对象引用其他三个类的对象。要解决这个问题,策略模式会帮助我吗?如果是的话请给我 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?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
您需要查看 Objective-C 的 协议机制。这是一个具有单个必需方法的简单协议:
然后声明一个实现该协议的类:
该实现必须提供
-execute
方法(因为它被声明为@required
):您可以创建一个类似的
ConcreteStrategyB
类,但我不会在这里展示它。最后,创建一个具有维护当前策略的属性的上下文类。
这是实现。委托给策略的
-execute
方法的方法恰好也被称为 -execute,但并非必须如此。现在我将创建几个实例并使用它们:
控制台输出显示策略已成功更改:
请注意,如果协议未指定
@required
,则该方法是可选的。在这种情况下,上下文需要检查策略是否实现了该方法:这是一个常见的 Cocoa 模式,称为 委托。有关 Cocoa 中的委派和其他设计模式的更多信息,
You'll want to look at Objective-C's protocol mechanism. Here's a simple protocol with a single required method:
Then you declare a class that fulfills that protocol:
The implementation must provide the
-execute
method (since it was declared as@required
):You can make a similar
ConcreteStrategyB
class, but I'm not going to show it here.Finally, make a context class with a property maintaining the current strategy.
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.Now I'll make a few instances and put them to use:
The console output shows that the strategy was successfully changed:
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:This is a common Cocoa pattern called delegation. For more information on delegation and other design patterns in Cocoa, see this.
这是一个更具体的例子。您可以将每个项目放入单独的文件中。为了便于理解,我将所有内容都放在一个文件中。
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.