1、功能模块独立
2、高扩展低耦合
3、抽象性复用性
整理这些设计模式的目的:从简单的代码中体会每个设计模式的灵魂所在。
偶然发现了一个对设计模式介绍的简单明了的网站:
http://c.biancheng.net/view/1317.html
单例模式:最简单和常用的一种,仅且只能有一个对象实例 (全局的)从而实现属性共享。因为我们使用Js/Ts去书写的所以就不考虑多线程的问题了,有兴趣可以搜索一下C++,Java的设计模式。
优点:… … …
缺点:… … …
一、比较常用的两种写法懒汉/饿汉;根据代码可以看出只是在创建对象的时机不同而已,没有什么太多的区别使用哪种方式都可以,我个人习惯懒汉模式。
//懒汉模式
class Singleton {
private static instance: Singleton = null;
private constructor() { }
public static GetInstance(): Singleton {
if (!this.instance) {
this.instance = new Singleton();
}
return this.instance;
}
}
//饿汉模式
class Singleton {
private constructor() { }
private static instance: Singleton = new Singleton();
public static GetInstance(): Singleton {
return this.instance;
}
}
//其他脚本使用的时候
Single.GetInstance().xx
二、上面两种方式书写比较直观,但是工程比较大的情况下就感觉每次都这么写比较麻烦,所以有了第二种单例模板
class Singleton{ private static instance: any = null; public static GetInstance (c: { new(): T }): T { if (this.instance == null) { this.instance = new c(); } return this.instance; } } //继承单例模板 class SoundManager extends Singleton { public test() { } } //其他脚本使用 SoundManager.GetInstance(SoundManager).test();



