介绍
创建型模式就是创建对象的模式,抽象了实例化的过程。它帮助一个系统独立于如何创建、组合和表示它的那些对象。也就说对创建对象的过程进行了封装,作为客户程序仅仅需要去使用对象,而不再关心创建对象过程中的逻辑。
单例模式
一个类仅有一个实例,不管什么时候我们要确保该类的只有一个对象实例存在。
这个在游戏中用的比较多,比如打砖块游戏中,在砖块类中和挡板类中都使用了小球这个类。
但是小球这个类的属性都是变化的,而小球只能是一个单独的实例。这个时候就需要单例模式
1 2 3 4 5 6 7
| class Singleton { private constructor() { } private static instance: Singleton = new Singleton() public static getInstance(): Singleton { return this.instance } }
|
简单工厂模式
一个创建对象的类,这个类封装实例化对象行为
这个在游戏中用的比较多,比如打飞机游戏中有多种飞机,可以用工厂模式创建相应的飞机实例
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33
| interface Product { }
class Product1 implements Product { constructor() { } } class Product2 implements Product { constructor() { } }
class SimpleFactory { public static createProduct(type: number): Product { const mp = { 1: new Product1(), 2: new Product2() } return mp[type] } }
abstract class AbstractFactory { public abstract createProduct(type: number): Product }
class Factory extends AbstractFactory { constructor() { super() } public createProduct(type: number): Product { const mp = { 1: new Product1(), 2: new Product2() } return mp[type] } }
|