포스트

[Creational Pattern] 프로토타입 패턴 (Prototype Pattern)

Design Pattern / Creational Pattern

프로토타입 패턴의 정의와 해당 디자인 패턴의 예제 코드를 통한 이해 및 설명 정리

개념

  • 실제 제품을 만들기에 앞서 테스트를 위한 샘플 제품을 만드는데 이때, 샘플 제품을 프로토타입이라고 함

  • 객체를 생성하는데 비용이 많이 들고, 비슷한 객체가 이미 있는 경우에 사용되는 생성 패턴 중 하나

    • 즉, 프로토타입 패턴은 원본 객체를 새로운 객체에 복사하여 필요에 따라 수정하는 메커니즘을 제공

패턴 구조

prototype

예제 코드

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
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
// Prototype Pattern 기본
let vehiclePrototype = {
  init: function (carModel) {
    this.model = carModel;
  },
  getModel: function () {
    console.log(`The model of this vehicle is ${this.model}`);
  },
};

const vehicle = (model) => {
  function F() {}
  F.prototype = vehiclePrototype;

  let f = new F();
  f.init(model);

  return f;
};

let car = vehicle("Tesla Model X");

car.getModel(); // Tesla Model X

// 메소드를 외부에서 Prototype에 지정
class Car {
  constructor(make, model, level, color, warranty) {
    this.make = make;
    this.model = model;
    this.level = level;
    this.color = color;
    this.color = color;
    this.warranty = warranty;
  }
  getInfo() {
    return console.log(
      "----------------------------------------------------\n" +
        `${this.make}, ${this.model}, ${this.level}, ${this.color}, ${this.warranty}`
    );
  }
}

let newCar = new Car("Tesla", "Model X", "Sedan", "White", "5 Year");

Car.prototype.zeroback = function () {
  return console.log("2.9 seconds");
};

newCar.getInfo(); // Tesla, Model X, Sedan, White, 5 Year
newCar.zeroback(); // 2.9 seconds

참고한 출처 사이트

Refactoring GURU

Inpa Dev Blog (디자인 패턴)

이 기사는 저작권자의 CC BY 4.0 라이센스를 따릅니다.