设计模式学习篇-原型模式

49 阅读1分钟

1.概念

就是基于已有的对象进行拷贝的方式创建对象就叫做原型模式。JavaScript语言就是基于原型设计的语言。

2.为什么要用原型模式

是为了解决创建大量对象时提升性能,根据不同的情况使用深拷贝和浅拷贝

3.举例说明

游戏中创建对象一般都会使用Clone之类的方法创建一个新对象。以下例子只是实现了浅拷贝。


interface IClone {
    clone();
}

class Role implements IClone {

    private _name: string = '';
    public get name(): string {
        return this._name;
    }
    public set name(value: string) {
        this._name = value;
    }
    private _lvl: number = 0;
    public get lvl(): number {
        return this._lvl;
    }
    public set lvl(value: number) {
        this._lvl = value;
    }
    private _skill: number[] = [];
    public get skill(): number[] {
        return this._skill;
    }
    public set skill(value: number[]) {
        this._skill = value;
    }

    clone(): Role {
        let role = new Role();
        role.name = this._name;
        role.lvl = this._lvl;
        role.skill = this._skill;
        return role;
    }
}

let role = new Role();
role.name = 'test';
role.lvl = 1;
role.skill = [1, 2, 3];

let role2 = role.clone();
console.log(role2);
role2.lvl = 3;
console.log(role2);