简体   繁体   English

iOS 设计模式实现

[英]iOS Design Pattern Implementation

I'm struggling with design patterns and would like to follow best practices while rewriting my current app from Objective-C to Swift.我在设计模式方面苦苦挣扎,并希望在将我当前的应用程序从 Objective-C 重写为 Swift 时遵循最佳实践。

I have a game where a player gets extra scores/or special prizes for, let's say, solving a certain amount of levels.我有一个游戏,玩家可以通过解决一定数量的关卡获得额外的分数/或特别奖品。 There are several milestones to be reached (such as 10 levels completed/50 levels completed).有几个里程碑需要达到(例如完成 10 个级别/完成 50 个级别)。 I have different game modes, so I have several subclasses of a Gameplay class.我有不同的游戏模式,所以我有几个 Gameplay 类的子类。 After each player's turn -checkSolution is being invoked to check whether the player solved the level.在每个玩家轮到之后-checkSolution被调用来检查玩家是否解决了这个关卡。 In case of success I increment the player's games score and send him to a new level .如果成功,我会增加玩家的游戏分数并将他发送到一个新的级别。 And here I also call -checkForMilestone of ScoreManager class to check whether any of the milestones has been reached.在这里,我还调用-checkForMilestone类的 -checkForMilestone 来检查是否已达到任何里程碑。

I'm not sure whether it is ok to call -checkForMilestone inside -checkSolution .我不确定在-checkSolution调用-checkForMilestone是否可以。 Or it might be better to create a callback using blocks or use KVO to observe (from ScoreManager class) whether the player's score was changed and then react appropriately.或者最好使用块创建回调或使用 KVO 来观察(从 ScoreManager 类)玩家的分数是否发生变化,然后做出适当的反应。

I would keep things simple.我会保持简单。 You can use KVO, events or other methods but from your description I can't see any benefit but adding complexity to the code and making things harder to debug.您可以使用 KVO、事件或其他方法,但从您的描述中,我看不出任何好处,只会增加代码的复杂性并使调试变得更加困难。 If you are already calling checkSolution() and you know this is the only place that will trigger a milestone change, then you should keep these two methods tight together.如果您已经在调用 checkSolution() 并且您知道这是唯一会触发里程碑更改的地方,那么您应该将这两个方法紧密结合在一起。 If on the other hand, milestones can be decoupled from successful solutions, eg player buying them with micro-payments or friends contributions adding to the player's milestones, then you can create an observable pattern on the score or whatever triggers things to get updated.另一方面,如果里程碑可以与成功的解决方案分离,例如玩家用小额付款购买它们或将朋友的贡献添加到玩家的里程碑,那么您可以在分数上创建一个可观察的模式或任何触发事物更新的东西。

First, good on you for even considering this.首先,即使考虑到这一点,也对你有好处。 The key concepts involved in the decision are "scope of responsibility" and "separation of concerns".决策中涉及的关键概念是“责任范围”和“关注点分离”。

You can likely determine the better option by considering:您可以通过考虑以下因素来确定更好的选择:

  1. What events could trigger a milestone being reached?哪些事件可以触发达到里程碑?
  2. What class is responsible for that action?哪个类负责该操作?
  3. Could a milestone be achieved separately from a level being solved?里程碑是否可以与正在解决的级别分开实现?

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM