【1/25】将Game改写为单例模式(Singleton Pattern)

169448949

共 1003字,需浏览 3分钟

 · 2021-01-28

00586856f3ee1bd86b82b2243ca7b9d7.webp

这是《小游戏从0到1设计模式重构》系列内容第1篇,所有源码及资料在“程序员LIYI”公号回复“小游戏从0到1”获取。

Game的实例在游戏时只有一个,现在我们首先将Game类改造为一个单例。所谓单例,就是运行时只有一个实例。Game.js代码改造如下:

 

// 游戏对象
class Game {
// 单例
static getInstance() {
if (!this.instance) {
this.instance = new Game()
}
return this.instance;
}
...

 

但是这个代码是有问题的,因为我们在Game.js文件的下方通过new关键字实例化过这个类:

 

/// 开始
const game = new Game()
GameGlobal.game = game
game.init()
game.start()

 

有两种方法解决这个问题。一种是修改单例方法getInstance代码的实现,将全局单例的实例化放在结构器中:

 

class Game {
// 单例
static getInstance() {
// if (!this.instance) {
// this.instance = new Game()
// }
return this.instance;
}
...
constructor() {
if (!Game.instance) {
Game.instance = this
}
}
...

 

另一种方法是修改Game.js文件的底部代码,在消费代码处实例化Game类的方式:

 

/// 开始
// const game = new Game()
const game = Game.getInstance()
GameGlobal.game = game
...

 

我们在这里采用第二种方法。将Game单例化,将为我们接下来应用其它设计模式打下基础。除了可以使用Game.getInstance()获取当前游戏的实例,还可以通过全局变量GameGlobal.game获取,第二种获取方式我们将在下一小节使用。

 

阶段源码


本小节阶段源码见:disc/第五章/5.1.1。


我讲明白没有,欢迎提问。

2021年1月26日

浏览 30
点赞
评论
收藏
分享

手机扫一扫分享

举报
评论
图片
表情
推荐
点赞
评论
收藏
分享

手机扫一扫分享

举报