cover

Prototype 模式:複製比建立更快

Prototype 模式透過複製現有物件來建立新物件,避免重複初始化成本。

classDiagram
    class Prototype {
        <<interface>>
        +clone()* Prototype
    }
    class UIComponent {
        -width : Number
        -height : Number
        -color : String
        +clone() UIComponent
        +render() String
    }
    Prototype <|.. UIComponent
    UIComponent ..> UIComponent : clone() 產生副本

使用情境

  1. UI 元件複製:複製元件模板再微調。
  2. 遊戲物件生成:快速產生敵人或道具。
  3. 設定物件:基礎配置複製。

實作範例

Prototype 模式:複製機快速產出多個變體

class UIComponent {
  constructor(width, height, color) {
    this.width = width;
    this.height = height;
    this.color = color;
  }
 
  clone() {
    return Object.assign(Object.create(Object.getPrototypeOf(this)), this);
  }
 
  render() {
    return `<div style="width:${this.width}px;height:${this.height}px;background:${this.color}"></div>`;
  }
}
 
const buttonPrototype = new UIComponent(100, 40, 'blue');
const confirmButton = buttonPrototype.clone();
confirmButton.color = 'green';
 
console.log(confirmButton.render());

優點

  • 初始化成本低
  • 可動態新增原型

缺點

  • 深層複製需要額外處理

延伸閱讀