Web/JavaScript

[Design Pattern] 7.Prototype Pattern

태애니 2023. 11. 17. 23:47
728x90

https://meongae.tistory.com/97

 

[디자인 패턴] ES6로 구현하는 디자인 패턴

※ 디자인 패턴 종류 ▶ 생성패턴 Constructor Factory Abstract Factory Prototype Singleton Builder ▶ 구조 패턴 Adapter Composite Module Decorator Facade Proxy FlyWeight Bridge ▶ 행동 패턴 Chain of Responsibility Command Observer Iter

meongae.tistory.com

 

JavaScript는 Object의 create() 메소드를 활용하여 손쉽게 구현 가능하다

 

 

 

 

 

const car = {
  noOfWheels: 4,
  start() {
    return `start ${this.noOfWheels}`;
  },
  stop() {
    return `stop ${this.noOfWheels}`;
  },
};

const myCar1 = Object.create(car, { owner: { value: 'Mung1' } });
const myCar2 = Object.create(car, { owner: { value: 'Mung2' } });

console.log(myCar1.__proto__ === car); // true
console.log(myCar2.__proto__ === car); // true

myCar2.noOfWheels += 10

console.log(myCar1.start()) // start 4
console.log(myCar1.stop()) // stop 4
console.log(myCar1.noOfWheels) // 4
console.log(myCar1.owner)  // Mung1

console.log(myCar2.noOfWheels) // 14
class Car {
  constructor (_wheels) {
    this.noOfWheels = _wheels;
  }
  
  start() {
    return `start ${this.noOfWheels}`;
  }
  
  stop() {
    return `stop ${this.noOfWheels}`;
  }
}

const car = new Car(4);

const cloneCar1 = Object.create(car, { owner: { value: 'Mung1' } });
const cloneCar2 = Object.create(car, { owner: { value: 'Mung2' } });

console.log(cloneCar1.__proto__ === car); // true
console.log(cloneCar2.__proto__ === car); // true

cloneCar2.noOfWheels += 10

console.log(cloneCar1.start()) // start 4
console.log(cloneCar1.stop()) // stop 4
console.log(cloneCar1.noOfWheels) // 4
console.log(cloneCar1.owner)  // Mung1

console.log(cloneCar2.noOfWheels) // 14
728x90