반응형
소프트웨어 디자인 패턴 중 Structural Pattern(구조 패턴) 은 객체나 클래스들을 조합하여 더 크고 유연한 구조를 설계하는 데 초점을 맞춥니다.
자바스크립트는 동적으로 객체를 다룰 수 있는 특성이 강해, 구조 패턴을 구현하는 데 매우 적합한 언어입니다.
🧱 Structural Pattern이란?
Structural Pattern은 여러 객체나 클래스를 결합하여 새로운 기능을 구성하거나 기존 인터페이스를 변경하지 않고 구조를 확장하는 방식입니다.
대표적인 Structural 패턴 종류
- Adapter Pattern (어댑터 패턴)
- Decorator Pattern (데코레이터 패턴)
- Facade Pattern (퍼사드 패턴)
- Proxy Pattern (프록시 패턴)
- Composite Pattern (컴포지트 패턴)
- Bridge Pattern (브리지 패턴)
- Flyweight Pattern (플라이웨이트 패턴)
⚙️ 패턴별 설명 및 예시
1. Adapter Pattern
class OldPrinter {
print() {
console.log("Old printer printing...");
}
}
class NewPrinter {
output() {
console.log("New printer outputting...");
}
}
class PrinterAdapter {
constructor(newPrinter) {
this.newPrinter = newPrinter;
}
print() {
this.newPrinter.output();
}
}
const newPrinter = new NewPrinter();
const adapter = new PrinterAdapter(newPrinter);
adapter.print();
장점
- 기존 코드 변경 없이 새로운 시스템에 호환 가능
단점
- 구조가 복잡해질 수 있음
2. Decorator Pattern
function Coffee() {
this.cost = function () {
return 5;
};
}
function Milk(coffee) {
this.cost = function () {
return coffee.cost() + 1.5;
};
}
const simpleCoffee = new Coffee();
const milkCoffee = new Milk(simpleCoffee);
console.log(milkCoffee.cost()); // 6.5
장점
- 객체의 기능을 유연하게 확장 가능
단점
- 데코레이터가 많아지면 관리가 어려움
3. Facade Pattern
class CPU {
start() { console.log("CPU started"); }
}
class Memory {
load() { console.log("Memory loaded"); }
}
class HardDrive {
read() { console.log("Hard drive reading"); }
}
class Computer {
constructor() {
this.cpu = new CPU();
this.memory = new Memory();
this.hd = new HardDrive();
}
start() {
this.cpu.start();
this.memory.load();
this.hd.read();
}
}
const myComputer = new Computer();
myComputer.start();
장점
- 복잡한 시스템을 간단하게 사용할 수 있게 함
단점
- 퍼사드에 과도한 책임이 집중될 수 있음
4. Proxy Pattern
const user = {
name: "Alice",
age: 30
};
const userProxy = new Proxy(user, {
get(target, prop) {
console.log(`Getting ${prop}`);
return target[prop];
},
set(target, prop, value) {
console.log(`Setting ${prop} to ${value}`);
target[prop] = value;
return true;
}
});
userProxy.age = 31;
console.log(userProxy.name);
장점
- 객체 접근을 제어하거나 감시할 수 있음
단점
- 성능 저하 발생 가능
✅ 결론
Structural Pattern은 객체 간의 관계를 보다 명확하고 유연하게 만들어줍니다.
복잡한 시스템의 내부 구현을 숨기거나, 새로운 기능을 기존 객체에 덧붙이거나, 인터페이스 호환을 가능하게 하는 등 다양한 상황에서 활용됩니다.
자바스크립트처럼 유연한 언어에서는 이러한 패턴의 도입이 코드 품질을 크게 향상시킬 수 있습니다.
반응형
'Programing > javascript' 카테고리의 다른 글
| 자바스크립트 Singleton Pattern (0) | 2025.04.19 |
|---|---|
| 자바스크립트 Factory Pattern (0) | 2025.04.19 |
| 자바스크립트 Constructor Pattern (0) | 2025.04.19 |
| 자바스크립트의 Behavioral 패턴: 객체 간의 소통을 설계하다 (0) | 2025.04.19 |
| 자바스크립트의 Creational 패턴: 객체 생성의 정석 (0) | 2025.04.19 |
| 💻 숫자를 한글 숫자 표기로 변환 (1) | 2025.04.18 |
| 💰 숫자를 한글로 금액 단위로 표현 (0) | 2025.04.18 |
| 📷 JavaScript로 이미지 리사이징 후 PHP로 업로드하는 방법 (1) | 2025.04.16 |