我有一个游戏类和一个多人类,它为定义的游戏处理所有网络玩家的东西:
export interface Multiplayer{
game: Game
start()
}
export class WebSocketMultiplayer implements Multiplayer{
constructor(public game: Game){}
start(){}
}反版本配置:
container.bind<Game>('Game').to(BasicGame)
container.bind<Multiplayer>('Multiplayer').to(WebSocketMultiplayer)现在我想创建、配置和运行游戏,然后再运行多人游戏。
const game = kernel.get<Game>('Game')
game.run()
const multiplayer = kernel.get<Multiplayer>('Multiplayer')
multiplayer.start()但是我应该如何将游戏实例传递给Multiplayer构造函数呢?如果我要在@inject构造函数中使用WebSocketMultiplayer,它就会创建另一个游戏实例。
我现在使用的临时解决方案是在多人游戏启动函数中传递游戏实例
start(game: Game){
this.game = game
}但是,它应该如何处理倒装呢?
发布于 2017-04-02 23:11:36
你可以尝试一些事情。
第一个选项是使用inSingletonScope方法:
container.bind<Game>('Game').to(BasicGame).inSingletonScope();您可以了解更多关于范围这里的知识。
第二个选择是使用工厂:
container.bind<Game>('Game').to(BasicGame);
container.bind<Multiplayer>('Multiplayer').to(WebSocketMultiplayer);
container.bind<() => Game>("GameFactory").toFactory<Game>((context: interfaces.Context) => {
const game = context.container.get<Game>("Game");
game.run();
return () => game;
});
class WebSocketMultiplayer implements Multiplayer{
public game: Game;
constructor(@inject("GameFactory") gameFactory: () => Game){
this.game = gameFactory();
}
start(){}
}如果game.run()是异步的,那么您将需要一个异步工厂(AKA 提供程序)。
https://stackoverflow.com/questions/43165335
复制相似问题