1-1. 모듈 패턴 싱글톤
const singleton = (function() {
let instance;
function createInstance() {
// 실제 인스턴스 생성 로직
return { /* ... */ };
}
return {
getInstance: function() {
if (!instance) {
instance = createInstance();
}
return instance;
},
};
})();
const instance1 = singleton.getInstance();
const instance2 = singleton.getInstance();
console.log(instance1 === instance2); // true
1-2. 클래스 기반 싱글톤
class Singleton {
constructor() {
if (!Singleton.instance) {
Singleton.instance = this;
}
return Singleton.instance;
}
}
const instance1 = new Singleton();
const instance2 = new Singleton();
console.log(instance1 === instance2); // true
class Latte {
constructor() {
this.name = "라떼"
}
}
class Espresso {
constructor() {
this.name = "에소프레쏘"
}
}
class LatteFactory {
static createCoffe() {
return new Latte()
}
}
class EspressoFactory {
static createCoffe() {
return new Espresso();
}
}
const factoryList = { LatteFactory, EspressoFactory }
class CoffeeFactory {
static createCoffee(type) {
const factory = factoryList[type]
return factory.createCoffe()
}
}
const main = () => {
// 라떼 주문
const coffee = CoffeeFactory.createCoffee
}
일단 프록시 객체에 대해서 먼저 알아보자. 프록시(proxy)는 객체를 감싸고, 해당 객체에 접근하려는 시도를 가로채거나 수정하는 기능을 제공하는 객체이다. 이를 통해 객체의 동작을 변경하거나 제어할 수 있다. 대리자라고 생각하면 될 거 같다.
const targetObject = {
name: 'John',
age: 30,
};
const handler = {
get(target, property) {
console.log(`Accessing property: ${property}`);
return target[property];
},
};
const proxy = new Proxy(targetObject, handler);
console.log(proxy.name); // 결과: "Accessing property: name"와 함께 "John" 출력
console.log(proxy.age); // 결과: "Accessing property: age"와 함께 30 출력
위 예시에서
targetObject
는 원본 객체이다.handler
객체는 프록시 동작을 정의한 객체입니다.get
메서드를 정의하여 프록시가 속성에 접근할 때 동작을 지정할 수 있다.get
메서드는 두 개의 인자를 받는다.
target
: 프록시로 감싸진 원본 객체(targetObject)property: 접근하려는 속성 이름
new Proxy(target, handler)
를 사용하여targetObject
를 감싸는 프록시를 생성.
프록시는 원본 객체의 동작을 변경하거나 확장할 수 있다.
proxy.name
과proxy.age
는 프록시를 통해 원본 객체의 속성에 접근하는 코드이고, 이 때get
메서드가 실행되며,property
에 해당하는 속성에 접근하는 동작을 수행하게된다.console.log
를 사용하여"Accessing property: name"
과"Accessing property: age"
가 각각 출력되고, 실제 속성 값이 반환 받게 된다.
const proxy = new Proxy(target, {
set(obj, prop, value) {
if (value !== obj[prop]) {
const prev = obj[prop]
obj[prop] = value
callback(`${prop}가 [${prev}] >> [${value}]로 변경되었읍니다.`)
}
return true
}
})
return proxy
}
const a = {
"수빈" : "커플"
}
const b = createReactiveObject(a, console.log)
b.수빈 = "솔로"
b.수빈 = "커플"
// 수빈이 [커플] >> [솔로]로 변경