定义:
单例模式:确保一个类只有一个实例,并提供一个全局访问点。
单例模式实在是太简单了,主要是注意线程安全问题;
比如一个单机游戏,游戏里只有一个玩家,那么这个玩家就可以设置成单例;
代码:
class Player {
private static instance?: Player
public static getInstance() {
if (!Player.instance) {
Player.instance = new Player()
}
return Player.instance
}
private HP: number = 0
private MP: number = 0
public setHPMP(HP: number, MP: number) {
this.HP = HP
this.MP = MP
}
public attack() {
console.log('魔法攻击...')
this.MP -= 10
console.log('MP -10')
}
public showStatus() {
console.log('HP: ' + this.HP + ', MP: ' + this.MP)
}
}
Player.getInstance().setHPMP(100, 100)
Player.getInstance().attack()
Player.getInstance().showStatus()
输出结果:
[LOG]: 魔法攻击...
[LOG]: MP -10
[LOG]: HP: 100, MP: 90
网友评论