一、單例模式的應用場景
單例模式是一種常見的設計模式,其應用場景也非常廣泛。單例模式通常只允許一個實例存在,可以用於創建全局唯一的對象。在使用原型模式實現單例模式時,先創建一個原型對象,然後通過克隆出多個相同的實例。
class Singleton { constructor() { if (!Singleton.instance) { this.name = 'I am a Singleton'; Singleton.instance = this; } return Singleton.instance; } getName() { console.log(this.name); } } class SingletonPrototype { constructor() { this.name = 'I am a Singleton by Prototype'; } clone() { return Object.create(this); } } const singletonPrototype = new SingletonPrototype(); const instance1 = singletonPrototype.clone(); const instance2 = singletonPrototype.clone(); instance1.getName(); instance2.getName(); console.log(instance1 === instance2); // true
二、js原型鏈的應用場景
原型鏈是Javascript中非常重要的概念,所有的Javascript對象都是通過原型鏈進行繼承的。原型鏈的應用場景包括創建漂亮的圖表、創建獨立的JavaScript庫和插件、實現不可變性等等。
function Person(name) { this.name = name; } Person.prototype.sayName = function() { console.log(this.name); }; function Student(name, grade) { this.grade = grade; Person.call(this, name); } Student.prototype = Object.create(Person.prototype); Student.prototype.constructor = Student; Student.prototype.sayGrade = function() { console.log(this.grade); }; const student = new Student('Tom', 'A'); student.sayName(); student.sayGrade();
三、適配器模式應用場景
適配器模式用於解決兩個不兼容的接口之間的問題。原型模式適配器可以將一個類的接口轉換為客戶所期望的另一種接口。
class Target { request() { return 'Target: Default behavior'; } } class Adaptee { specificRequest() { return 'Adaptee: Specific behavior'; } } class Adapter extends Target { constructor(adaptee) { super(); this.adaptee = adaptee; } request() { return `Adapter: (translate '${this.adaptee.specificRequest()}' to the request())`; } } const adaptee = new Adaptee(); const adapter = new Adapter(adaptee); const result = adapter.request(); console.log(result);
四、原型模型適用場景
原型模式主要應用於創建複雜對象的場景,通過克隆一個預設對象來創建新的對象實例。例如在大多數遊戲中,角色的創建過程很常見,可以使用原型模型來抽象出角色的特徵和屬性,然後通過克隆來創建多個實例。
class Enemy { constructor() { this.name = ''; this.attack = 0; this.defend = 0; this.speed = 0; } clone() { return Object.create(this); } } const boss = new Enemy(); boss.name = 'Big Boss'; boss.attack = 50; boss.defend = 30; boss.speed = 20; const enemy1 = boss.clone(); enemy1.name = 'Enemy 1'; const enemy2 = boss.clone(); enemy2.name = 'Enemy 2'; console.log(boss); console.log(enemy1); console.log(enemy2);
五、設計模式及其應用場景
原型模式是23種設計模式之一,主要用於創建複雜對象的場景。
在一些需要頻繁創建新對象的場景下,使用原型模式可以節省創建時間和系統資源,提升性能。此外,原型模式也支持動態配置對象,提高了系統的可擴展性。
因此,在需要頻繁創建、自定義或者動態配置對象的場景下,建議使用原型模式。
原創文章,作者:QFOSD,如若轉載,請註明出處:https://www.506064.com/zh-hant/n/351703.html