假设我想要创建一个简单的toe游戏,并且我为游戏板建立了模型。我的问题是,我应该把管理这个董事会的逻辑放在哪里?例如。
export class Board{
boardString: string;
rows: string[];
separator: string;
constructor(boardString: string, separator: string = '|'){
this.boardString = boardString;
this.separator = separator;
this.rows = this.boardString.split('|');
}
}// inside model class
atIndex(index: number): string{
const atCol = index % this.rows.length;
const atRow = (index - atCol) / this.rows.length;
return this.rows[atRow][atCol];
}
isFinished(): boolean {
// check if game is finished
}
getRow(index): string{
return this.rows[index]
}vs
// or in the Service
atIndex(index: number): string{
const atCol = index % this.boardModel.rows.length;
const atRow = (index - atCol) / this.boardModel.rows.length;
return this.boardModel.rows[atRow][atCol];
}
isFinished(): boolean{
// check if game is finished
}
getBoardRow(index): string{
return this.boardModel.rows[index];
}我不知道我是否说得很清楚。抽搐脚趾这只是个例子。我想知道我应该把逻辑放在哪里来负责管理模型属性?我从文档中看到,所有的逻辑都应该是内部服务。但对我来说,在某些情况下,它更适合模型类(例如getter)。在模型类中保留方法是一种反模式吗?
使用此模型(GameService)
中。
发布于 2020-09-22 07:38:39
说I read from documentation that all logic should be inside services有点误导人。当然,这确实取决于逻辑在做什么,而且并不是所有的逻辑都应该在服务中。
对于Models来说,将一些逻辑保留在其中是非常有意义的。一个很好的例子是一些Modal或Notification类,它将在初始化后提供一些功能,比如close、onClose等等。假设您需要通过像notificationService.close(<notificationUniqueId)这样的服务来关闭通知。
您在示例中谈到了components。您提出的逻辑对于组件来说是非常好的。我甚至可以说这是将它放入组件中的最佳实践--它将使与UI的集成变得更干净和更简单,并且您的代码将更易于管理。
不过,我理解你的挣扎。有时,您的UI逻辑可能会扩展到多个组件。但是,我仍然不会将它放入Service中。就我个人而言,我试图将服务限制在a) performs some API calls、b) formats data in some way或c) manages state and actions throughout the application的逻辑上。在我最近的项目中,我们实现了另一种可注入的类型,我们称之为CommonUIHandler --这个类的子集在整个组件中处理重复逻辑。但是它创建了另一个抽象级别,并在不需要的时候阻止了传统服务的增长。
我相信如果你搜索Angular design patterns,你会发现很多有价值的资源。值得一提的一个例子可能是https://coryrylan.com/blog/angular-design-patterns-feature-services
https://stackoverflow.com/questions/63999811
复制相似问题