Typescript

Object-oriented programming (객체 지향 프로그래밍)

마손리 2022. 12. 21. 02:12

객체 지향 프로그래밍이란 이름 그대로 객체를 만드는데 최적화된 프로그래밍이다. 수십 수백개의 객체를 관리하는데 유용하다.

 

 

캡슐화

캡슐화란 데이터 혹은 함수를 캡슐안에 넣는것을 의미한다. 쉽게말해 class 안에 함수나 데이터들을 넣는 것이다.

const player = {
  name: "Mason",
  power: 10,
  speed: 5,
};
const calculateDPS = (power: number, speed: number) => {
  return power * speed;
};
const masonDPS = calculateDPS(player.power, player.speed);
console.log(masonDps);

게임에서 캐릭터 하나를 만든다고 가정했을때 player란 객체를 수동적으로 만들어주고 그 캐릭터의 대미지를 구하는 간단한 공식을 함수로 만들었다.

위와 같이 하나의 객체만을 다룰때는 상관이 없지만 수십 수백개의 객체를 생성해야 할때에는 객체를 하나씩 수동적으로 모두 만들어 주어야 하는 불편함이 있다.

 

이를 캡슐화 하면

class Player {
  constructor(
    public readonly name: string,
    private power: number,
    private speed: number
  ) {}
  dps() {
    return this.power * this.speed;
  }
}
const mason = new Player("Mason", 10, 5);
console.log(mason.dps());

생성자(constructor)를 통해 각 인스턴스(객체를 만드는 행위, 위의경우 new Player()가 된다.) 생성에 필요한 값들을 정의 해줄수 있으며 class안에 함수도 넣어 줄수있다.

또한 private, public, readonly와 같은 속성들을 부여해 줌으로써 각 객체의 데이터를 보호해 줄수도 있다.

 

 

상속화

상속화란 부모클래스와 자식클래스를 정해서 부모클래스의 속성을 자식클래스에 상속시켜 주는것을 의미하낟.

상속화를 사용하면 코드를 더 작은단위로 나누고 상황에 맞게 재사용 할수있다.

class Person {
  private fullName:string
  constructor(
    private firstName: string,
    private lastName:string
  ) {
    this.fullName = `${this.firstName} ${this.lastName}`
  }
  public greeting() {
    return `Hi my name is ${this.fullName}`
  }
}


class Actor extends Person{
  constructor(
    firstName: string,
    lastName: string,
    private oscar: number
  ) {
    super(firstName,lastName)
}
}

class Singer extends Person{
  constructor(
    firstName: string,
    lastName: string,
    private billBoard: number
  ) {
    super(firstName,lastName)
}
}

위의 코드를 보면 Actor와 Singer 두 클래스의 생성자에 firstName과 lastName이 공통적으로 들어간다. 이런 경우 다른 하나의 부모클래스를 생성후 extends를 이용하여 두 자식 클래스에 상속 시켜준뒤 상속받은 생성자를 super()를 이용해 불러와 주면된다.

위의 경우 부모클래스의 fullName을 구하는공식과 greeting()이라는 함수 또한 자식클래스에서 사용이 가능하다.

 

 

추상화

미술에서의 추상화는 대상의 형태를 구체적으로 표현하는것이 아니라 점, 선, 면 등을 이용한 표현을 나타낸다. 

OOP에서의 추상화는 직접적으로 데이터에 접근하는 것이아닌 설계만을 하여 자식클래스에 물려주게 되는 것이다.

abstract class User {
  constructor(
    protected firstName: string, //protected를 사용함으로써 자식class에서도 접근이 가능
    protected lastName: string
  ) {}
  abstract getFullName(): void; //추상메소드는 타입만 지정
}

class Player extends User {
  getFullName() {
    return `${this.firstName} ${this.lastName}`; // 자식 class에서 반드시 부모의 추상메소드를 만들어 주어야한다.
  }
}

위와 같이 abstract를 이용하여 추상화 클래스를 만들어준후 getFullName()이라는 추상메소드를 만들어 주었다.

이전의 상속화와 다르게 추상메소드는 직접적인 함수 구현이아닌 함수의 타입만을 지정해주며 물려받은 자식속성은 무조건 그 메소드를 구현시켜야한다. 

 

또한 추상화 클래스는 인스턴스를 생성 시키지못한다. 

 

다양화

다양화를 이용하면 같은 부모 클래스를 둔 다른 자식 클래스들을 다양성 있게 활용해 줄수 있다.

class User {
  public greeting(): string {
    return "안녕하세요";
  } /* 부모class의 메소드가 string을 반환한다면 자식속성또한 무조건 string으로 반환해야한다.
   혹은 위와같이 타입을 지정해주어 자식속성에서 다른타입을 반환하게 할수도 있다.*/
}

class 얼라이언스 extends User {}
class 호드 extends User {
  // 부모class의 메소드와 같은 이름이지만 메소드 오버라이딩을 통해 다른 값을 리턴해 준다.
  public greeting() {
    return "록타르 오가르!";
  }
}

위의 코드를 보면 얼라이언스 클래스의 경우 greeting() 메소드가 부모로부터 호출이 되지만 호드 클래스의 경우 메소드 오버라이딩을 통해 자신의 메소드가 호출이된다.

 

'Typescript' 카테고리의 다른 글

OOP를 이용하여 kiosk 시스템 만들기  (1) 2022.12.21
타입스크립트 심화  (0) 2022.12.20
타입스크립트 기초  (0) 2022.12.19