반응형
Constructor Pattern(생성자 패턴) 은 자바스크립트에서 객체를 생성하는 가장 기본적이면서도 강력한 방법 중 하나입니다. 이 패턴은 객체 지향 프로그래밍의 핵심 개념인 클래스와 유사한 구조를 제공하여, 코드를 구조적으로 구성하고 재사용성을 높이는 데 기여합니다.
🧱 Constructor Pattern이란?
Constructor Pattern은 생성자 함수를 통해 객체를 생성하는 방식입니다. 이 패턴은 자바스크립트에서 클래스가 도입되기 전부터 객체 생성을 위해 사용되어 왔으며, new 키워드와 함께 사용됩니다.
function User(name, role) {
this.name = name;
this.role = role;
this.introduce = function() {
return `Hi, I'm ${this.name}, a ${this.role}`;
};
}
const admin = new User("Alice", "Administrator");
console.log(admin.introduce());
또는 ES6 클래스 문법으로도 같은 패턴을 구현할 수 있습니다:
class User {
constructor(name, role) {
this.name = name;
this.role = role;
}
introduce() {
return `Hi, I'm ${this.name}, a ${this.role}`;
}
}
const user = new User("Bob", "Editor");
console.log(user.introduce());
✅ 장점
- 명확한 구조: 객체의 속성과 메서드를 구성하는 방식이 명확하여 가독성이 높음
- 다수 객체 생성 가능: 생성자 함수 하나로 유사한 객체를 손쉽게 여러 개 만들 수 있음
- 프로토타입 활용 가능: 공통 메서드를 prototype에 정의하여 메모리 효율을 높일 수 있음
User.prototype.sayBye = function() {
return `${this.name} says goodbye.`;
};
❌ 단점
- 함수 중복 생성: 메서드를 this.introduce = function()처럼 정의하면 객체마다 메서드가 중복 생성됨
- new 키워드 의존성: new 없이 호출할 경우 this가 전역 객체에 바인딩되어 오류 발생
- 상속 구조 구현이 복잡함: 자바의 클래식 상속보다 구현이 번거로움
const user = User("Charlie", "Viewer"); // this는 전역 객체
console.log(user); // undefined
🛠️ 실전 예시: 유저 관리 시스템
function Member(name, level) {
this.name = name;
this.level = level;
}
Member.prototype.access = function() {
if (this.level > 5) {
return `${this.name} has admin access.`;
}
return `${this.name} has user access.`;
};
const m1 = new Member("Diana", 3);
const m2 = new Member("Edward", 7);
console.log(m1.access()); // user access
console.log(m2.access()); // admin access
🧩 결론
Constructor Pattern은 자바스크립트에서 객체 생성의 기본이자, 클래스 기반 객체지향을 모방하는 데 매우 유용한 패턴입니다. 단순한 구조로 시작하여 프로토타입 기반 확장성까지 제공하지만, new 키워드의 사용에 주의해야 하며 복잡한 상속 구조에는 다른 패턴과 함께 사용하는 것이 좋습니다.
반응형
'Programing > javascript' 카테고리의 다른 글
자바스크립트 Builder Pattern (0) | 2025.04.19 |
---|---|
자바스크립트 Prototype Pattern (1) | 2025.04.19 |
자바스크립트 Singleton Pattern (0) | 2025.04.19 |
자바스크립트 Factory Pattern (0) | 2025.04.19 |
자바스크립트의 Behavioral 패턴: 객체 간의 소통을 설계하다 (0) | 2025.04.19 |
자바스크립트의 Structural 패턴: 객체 구조의 유연함을 설계하다 (0) | 2025.04.19 |
자바스크립트의 Creational 패턴: 객체 생성의 정석 (0) | 2025.04.19 |
💻 숫자를 한글 숫자 표기로 변환 (1) | 2025.04.18 |