Post

객체지향이란??

타입스크립트의 객체지향 프로그래밍 특징

클래스 (Classes)

타입스크립트에서 클래스는 객체의 특정 유형을 정의하는 틀로 사용됩니다. 클래스는 속성과 메서드를 포함할 수 있으며, 상속을 통해 기능을 확장할 수 있습니다

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
class Animal {
    name: string;
    constructor(name: string) {
        this.name = name;
    }
    move(distanceInMeters: number = 0) {
        console.log(`${this.name} moved ${distanceInMeters} meters.`);
    }
}

class Dog extends Animal {
    bark() {
        console.log('Woof! Woof!');
    }
}

const dog = new Dog("Buddy");
dog.bark();
dog.move(10);

인터페이스 (Interfaces)

인터페이스는 특정 구조를 클래스나 객체가 준수해야 할 형태로 정의합니다. 인터페이스를 통해 다양한 클래스에 일관된 구조를 제공할 수 있으며, 다형성을 실현할 수 있습니다.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
interface Movable {
    move(): void;
    stop(): void;
}

class Car implements Movable {
    move() {
        console.log("Car is moving");
    }
    stop() {
        console.log("Car stopped");
    }
}

class Bike implements Movable {
    move() {
        console.log("Bike is moving");
    }
    stop() {
        console.log("Bike stopped");
    }
}

추상 클래스 (Abstract Classes )

추상 클래스는 다른 클래스의 기반 클래스로 사용될 수 있으나, 자체적으로 인스턴스를 생성할 수 없습니다. 추상 클래스는 하나 이상의 추상 메서드를 포함할 수 있으며, 이 메서드는 파생 클래스에서 구현되어야 합니다.

1
2
3
4
5
6
7
8
9
10
11
12
13
abstract class Animal {
    abstract makeSound(): void;
    move(): void {
        console.log("roaming the earth...");
    }
}

class Snake extends Animal {
    makeSound() {
        console.log("Hiss");
    }
}

캡슐화 (Encapsulation)

타입스크립트는 캡슐화를 통해 객체의 상세 구현 내용을 숨기고, 외부에서는 오직 객체가 제공하는 API만을 통해 상호작용할 수 있도록 합니다. 이를 위해 public, private, protected 같은 접근 제어자를 사용합니다.

1
2
3
4
5
6
7
8
9
10
class Employee {
    private name: string;
    constructor(name: string) {
        this.name = name;
    }
    public introduceSelf() {
        console.log(`Hi, I am ${this.name}`);
    }
}

객체지향 프로그래밍의 이점

타입스크립트에서 객체지향적 접근 방식을 사용함으로써 코드의 재사용, 확장성 및 유지 관리가 쉬워집니다. 또한, 큰 프로젝트를 다루는 경우, 코드의 복잡성을 관리할 수 있는 체계적인 방법을 제공하며, 팀원 간의 협업과 코드의 일관성을 유지하는 데 큰 도움이 됩니다. 객체지향의 원칙들은 타입스크립트를 사용하여 모던 웹 애플리케이션을 개발하는데 있어 필수적인 요소입니다.

다음시간에 계속…

image

This post is licensed under CC BY 4.0 by the author.