我有实体Reward
,可以向玩家提供奖励。
因此,当满足所有条件时,将调用方法executeReward()
;
问题是:实现可能非常不同。例如,奖励
可以是给玩家金钱,或者开始全局 Activity ,或者给玩家另一个任务(与之前的任务无关)。 IE。我不知道会执行什么逻辑。这可以怎么设计呢?在模型和服务之间的通信方面。
我正在考虑的选项:
创建奖励服务,其中从
executeReward(RewardService rs)
方法调用不同的方法,但这会破坏“模型不了解服务”。在服务层编排逻辑。但这需要手动映射,这会破坏域中层次结构的全部目的。
这似乎都不是一个好的选择。有什么好的方法吗?
ps:奖励实体是通过hibernate从数据库获取的。因此,由于 hibernate 不插入服务,(可能)会出现复杂性。也就是说,据我所知,实体通常应该避免提供服务。
最佳答案
解决方案1
我将通过 Command behavioral design pattern 实现奖励逻辑.
例如引入具有一个 execute
方法的通用 Reward
接口(interface),并在其实现中封装各种奖励:MoneyReward
、QuestReward
等。此特定实现的一部分应该在其创建期间获得执行所需的所有内容:
class MoneyReward implements Reward {
MoneyReward(Player gamer, Depository money) {
...
}
@Override
public execute() {
...
}
}
...
class QuestReward implements Reward {
MoneyReward(Player gamer, Map territory) {
...
}
@Override
public execute() {
...
}
}
根据您的条件选择所需的奖励
实体后,您可以简单地进行奖励:
Raward gift = ...
gift.execute();
解决方案2
或者Strategy behavioral design pattern可以使用。
例如奖励
界面可能是这样的
interface Reward {
void execute(Player gamer);
}
可能的实现之一是
class MoneyReward implements Reward {
MoneyReward(Depository money) {
...
}
@Override
public execute(Player gamer) {
...
}
}
这里的MoneyReward
命令和策略有什么区别?
该命令封装了创建过程中执行所需的所有内容,并且可以为特定玩家使用一次。每次您想要奖励时,您都需要创建 MoneyReward
命令实例。
相反的MoneyReward
策略仅封装所有玩家之间进行重写所需的公共(public)服务。 MoneyReward
策略可以创建一次(例如像 Spring 单例)并在整个应用程序生命周期内重复使用。
注意:在这两个解决方案中,Depository
、Map
、Player
应该是定义良好的小型接口(interface),不会破坏Single Responsibility Principle 。
关于java - 如何设计模型和服务之间的交互?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39243388/