728x90
반응형
📌 객체지향 프로그래밍(OOP) - TypeScript로 자세히 정리
객체(Object)를 중심으로 설계하는 프로그래밍 패러다임으로, 캡슐화, 상속, 다형성, 추상화를 기반으로 함.
코드의 재사용성과 유지보수성을 높이는 핵심 개념.
1. OOP의 4대 원칙
객체지향 프로그래밍(OOP)의 핵심 개념은 다음과 같습니다.
원칙 설명
캡슐화 (Encapsulation) | 데이터를 외부에서 직접 접근하지 못하게 하고, 메서드를 통해 조작 |
상속 (Inheritance) | 부모 클래스의 속성과 메서드를 자식 클래스가 재사용 |
다형성 (Polymorphism) | 같은 인터페이스/부모 클래스를 공유하는 객체들이 서로 다른 동작을 할 수 있도록 함 |
추상화 (Abstraction) | 불필요한 세부사항을 숨기고, 중요한 부분만 노출 |
2. 캡슐화 (Encapsulation)
"객체의 데이터(속성)를 보호하고, 메서드를 통해서만 조작할 수 있도록 하는 개념"
✅ 2.1 TypeScript 예제: private와 getter/setter 사용
class BankAccount {
private balance: number;
constructor(initialBalance: number) {
this.balance = initialBalance;
}
// Getter: balance 조회
getBalance(): number {
return this.balance;
}
// Setter: balance 수정
deposit(amount: number): void {
if (amount <= 0) {
console.log("입금 금액은 0보다 커야 합니다.");
return;
}
this.balance += amount;
console.log(`💰 ${amount}원 입금 완료! 현재 잔액: ${this.balance}원`);
}
}
const myAccount = new BankAccount(5000);
console.log(myAccount.getBalance()); // ✅ 5000
myAccount.deposit(2000); // ✅ 7000
myAccount.deposit(-1000); // ❌ 입금 금액은 0보다 커야 합니다.
📌 설명
- private balance → BankAccount 클래스 외부에서 직접 balance 값 수정 불가.
- 메서드(getBalance(), deposit())를 통해서만 balance 값을 조작.
3. 상속 (Inheritance)
"부모 클래스의 속성과 메서드를 자식 클래스가 재사용할 수 있도록 하는 개념"
중복 코드를 줄이고, 객체 간의 계층 구조를 형성.
✅ 3.1 TypeScript 예제: extends를 사용한 상속
class Animal {
constructor(public name: string) {}
makeSound(): void {
console.log("동물이 소리를 냅니다.");
}
}
class Dog extends Animal {
constructor(name: string, public breed: string) {
super(name);
}
makeSound(): void {
console.log(`${this.name} (${this.breed})가 멍멍! 소리를 냅니다.`);
}
}
const myDog = new Dog("바둑이", "시바견");
myDog.makeSound(); // ✅ "바둑이 (시바견)가 멍멍! 소리를 냅니다."
📌 설명
- Dog 클래스는 Animal 클래스를 extends(상속) 받아 makeSound() 메서드를 재정의(오버라이딩)
- super(name) → 부모 클래스(Animal)의 생성자를 호출하여 name을 초기화.
4. 다형성 (Polymorphism)
"같은 부모 클래스를 공유하는 객체들이 서로 다른 동작을 할 수 있도록 하는 개념"
즉, 같은 메서드지만 서로 다른 동작을 수행할 수 있음.
✅ 4.1 TypeScript 예제: 인터페이스와 다형성 적용
interface Animal {
makeSound(): void;
}
class Cat implements Animal {
makeSound() {
console.log("야옹!");
}
}
class Dog implements Animal {
makeSound() {
console.log("멍멍!");
}
}
// 다형성 적용: 같은 타입(Animal)으로 서로 다른 동작 수행
const animals: Animal[] = [new Dog(), new Cat()];
animals.forEach(animal => animal.makeSound());
// ✅ "멍멍!"
// ✅ "야옹!"
📌 설명
- interface Animal을 사용하여 다형성 적용.
- Dog, Cat은 같은 makeSound() 메서드를 구현하지만, 서로 다른 동작 수행.
- animals.forEach(animal => animal.makeSound()); → 같은 메서드 호출이지만 실행 결과가 다름 (다형성 적용).
5. 추상화 (Abstraction)
"불필요한 세부사항을 숨기고, 중요한 부분만 노출"
즉, 핵심 로직만 정의하고, 세부 구현은 자식 클래스에서 수행.
✅ 5.1 TypeScript 예제: abstract class 사용
abstract class Shape {
abstract getArea(): number; // 추상 메서드 (구현 없이 선언만 함)
display(): void {
console.log(`도형의 면적: ${this.getArea()} cm²`);
}
}
class Circle extends Shape {
constructor(private radius: number) {
super();
}
getArea(): number {
return Math.PI * this.radius * this.radius;
}
}
class Rectangle extends Shape {
constructor(private width: number, private height: number) {
super();
}
getArea(): number {
return this.width * this.height;
}
}
const myCircle = new Circle(10);
const myRectangle = new Rectangle(5, 7);
myCircle.display(); // ✅ 도형의 면적: 314.159 cm²
myRectangle.display(); // ✅ 도형의 면적: 35 cm²
📌 설명
- abstract class Shape → 공통된 display() 메서드를 제공하지만, getArea()는 구현하지 않음.
- Circle, Rectangle 클래스에서 getArea()를 개별적으로 구현(오버라이딩).
- 추상화를 활용하면 객체의 핵심 기능을 정의하고, 개별 구현을 서브 클래스에 맡길 수 있음.
6. 객체지향 프로그래밍(OOP) 정리
원칙 설명 TypeScript 적용 방법
캡슐화 | 속성을 private 또는 protected로 보호하고, 메서드로 조작 | private 또는 getter/setter 사용 |
상속 | 부모 클래스를 extends하여 자식 클래스가 기능을 재사용 | extends 키워드 사용 |
다형성 | 같은 부모 클래스를 상속받거나 인터페이스를 구현한 객체들이 다른 동작 수행 | interface 또는 abstract class 활용 |
추상화 | 공통 기능을 정의하고, 구체적인 구현을 서브 클래스에서 수행 | abstract class 사용 |
🚀 결론
✔ 객체지향 프로그래밍(OOP)을 활용하면 유지보수성과 확장성이 높은 코드를 작성할 수 있다.
✔ TypeScript의 private, protected, abstract class, interface를 활용하여 OOP 원칙을 적용 가능.
✔ 캡슐화, 상속, 다형성, 추상화를 적절히 조합하면 견고한 설계를 만들 수 있다.
🔥 다음 단계 → SOLID 원칙 자세히 설명! 🚀
728x90
반응형
'CS > Algorithm' 카테고리의 다른 글
📌 디자인 패턴 (Design Patterns) – TypeScript로 상세 정리 (1) | 2025.02.02 |
---|---|
📌 SOLID 원칙 – 객체지향 프로그래밍의 핵심 설계 원칙 (0) | 2025.02.02 |
📌 객체지향 프로그래밍(OOP), SOLID 원칙, 디자인 패턴, DI - TypeScript 예제 포함 상세 설명 (0) | 2025.02.02 |
[CS] Typescript를 활용한 자료구조 중 Array, LinkedList (1) | 2024.12.19 |
[Algorithm] python - 경우의 수 문제 모음 및 필요 파이썬 문법 정리 (0) | 2024.11.26 |