单例模式
实例化单一对象,懒加载
//单例模式
class GameManagerSingleton
{
private constructor(){}
private static instance:GameManagerSingleton;
public static Instance()
{
if(!GameManagerSingleton.instance)
{
this.instance = new GameManagerSingleton();
}
return this.instance;
}
Init(){}
}
GameManagerSingleton.Instance().Init();
代理模式
根据不同的代理者,具体化实际方法操作
//代理模式
interface ICall
{
DealNum(x1:number,x2:number):number;
}
class NPC1 implements ICall
{
DealNum(x1: number, x2: number): number {
return x1 + x2;
}
}
class NPC2 implements ICall
{
DealNum(x1: number, x2: number): number {
return x1 - x2;
}
}
class Person
{
public delegate : ICall;
public DealNum(x1,x2) : number
{
let retNum = this.delegate.DealNum(x1,x2);
return retNum;
}
}
观察者模式
设置观察者后,对象的变更会告知观察者
//观察者模式
interface IObserver
{
nameChanged(newName);
}
class Test implements IObserver
{
//捕捉变化
nameChanged(newName : string)
{
console.log("NewName:"+newName)
}
}
class People
{
private name : string;
/**
*
*/
constructor() {
this.name = ""
}
public get Name()
{
return this.name;
}
public set Name(value)
{
if(this.name != value)
{
this.name = value;
//发生变化会向观察者发消息
for(let observer of this.Observers)
{
observer.nameChanged(this.name);
}
}
}
Observers : Array<IObserver> = new Array<IObserver>();
}
let People1 = new People()
let observer1 = new Test()
//设置观察者
People1.Observers.push(observer1)
//改变对象
People1.Name = "Tom"
工厂模式
游戏中构建item群体的常用模式
enum CarType
{
BMW,
Benz,
Audi,
}
class Car
{
name : string;
static CreateCar(type : CarType)
{
switch(type)
{
case CarType.BMW:
return new BMW();
case CarType.Benz:
return new Benz();
}
}
}
class BMW extends Car
{
/**
*
*/
constructor() {
super();
this.name = "BMW"
}
}
class Benz extends Car
{
/**
*
*/
constructor() {
super();
this.name = "Benz"
}
}
Car.CreateCar(CarType.Benz)
Car.CreateCar(CarType.BMW)