一、单例模式
1.预加载
class SoundManager{
static Instance = new SoundManager();
name: string = '单例'
private constructor() { }
}
console.log(SoundManager.Instance.name)
2.懒加载
class ISoundManager {
private static instance: ISoundManager = null;
private constructor() { }
name: string = '懒加载';
static Instance() {
if (!ISoundManager.instance) {
ISoundManager.instance = new ISoundManager();
}
return ISoundManager.instance;
}
}
console.log(ISoundManager.Instance().name)
二、 代理模式
interface ICalc {
calc(num1, num2): number;
}
class Npc1 implements ICalc{
calc(num1, num2) {
return num1 + num2;
}
}
class Npc2 implements ICalc{
calc(num1, num2) {
return num1 - num2;
}
}
class Person {
delegate: ICalc;
GetNum(num1, num2) {
let num = this.delegate.calc(num1, num2);
console.log(num)
}
}
let person = new Person();
person.delegate = new Npc2();
person.GetNum(3, 4);
person.delegate = new Npc1();
person.GetNum(3, 4);
三、观察者模式
interface IObserverf{
nameChanged(oldName,newName);
}
class Person{
private _name: string = '嘻嘻';
observers: Array<IObserverf> = new Array<IObserverf>();
set name(value: string) {
let oldName: string = this._name;
this._name = value;
for (let observer of this.observers) {
observer.nameChanged(oldName,this._name);
}
}
get name(){
return this._name;
}
}
class Test implements IObserverf {
nameChanged(oldName: string,newName: string) {
document.write("监听到变化,名字" + oldName + "变为" + newName);
}
}
let person = new Person();
let test = new Test();
person.observers.push(test);
person.name = "哈哈";
四、工厂模式
enum CarType{
Bmw,
Audi,
Benz
}
class Car {
name: string;
static Create(carType: CarType): Car {
let car: Car;
switch (carType) {
case CarType.Audi:
car = new Audi();
break;
case CarType.Benz:
car = new Benz();
break;
case CarType.Bmw:
car = new Bmw();
break;
}
return car;
}
}
class Bmw extends Car {}
class Benz extends Car {}
class Audi extends Car {}
let bmw = Car.Create(CarType.Bmw);
let bgenz = Car.Create(CarType.Benz);
let audi = Car.Create(CarType.Audi);
console.log(bmw,bgenz,audi)
|