728x90

개요

typescript로 Object Orient Programing(OOP)을 공부해 보자.
OOP의 주제로는 크게

  • encapsulation (캡슐화)
  • abstraction (추상화)
  • inheritance (상속)
  • polymorphism (다형성)
  • composition (포함)

위의 5가지에 대해 각각이 언제 쓰이고 어떻게 쓰이는지 예시와 함께 알아볼 것이다.

예시는 포켓몬스터 소드실드의 랭크게임의 파티짜기를 가지고 코드를 작성해 보도록 하겠다.

포켓몬스터 소드실드의 랭크게임을 모르는 사람을 위해 간략히 설명하자면

랭크게임을 하기위해선 1마리 이상 6마리 이하의 포켓몬의 파티를 꾸리게 된다.

그리고 이 6마리 포켓몬안에는 최대 1마리의 전설의 포켓몬을 가질 수 있다.(1전설 + 5일반 or 6일반)




class 없이

객체 지향으로 들어가기전에 객체 지향이 얼마나 좋은 개념인지 비교하기 위해 class를 사용하지 않은 절차 지향으로 구현해보자.

type Pokemon = {
  name:string;
  level: number;
};
const MINIMUM_LEVEL_REQUIRED : number = 50;
const pokemonArr : Pokemon[] = [{name:'이상해꽃'
                                 level:50},
                                {name:'리자몽'
                                 level:50},
                                {name:'거북왕',
                                 level;50}
                               ];
type Party= {
  pokemon : integer; //파티 포켓몬수
  hasLegendary:boolean; // 전설의 포켓몬 포함여부
};

funcion makeWeakParty(pokemon:readonly Pokemon[]): Party{
  if(pokemon.length()<1){
    throw new Error("no pokemon to participate");
  }
  pokemon.forEach((item)=>{
      if(item.level<MINIMUM_LEVEL_REQUIRED){
      throw new Error("too low level");
    }
  })
  return{
    pokemon,
    hasLegendary:false
  }
}

const myParty = makeWeakParty(pokemonArr);
console.log(myParty);



class 있이

이제 class 개념을 도입하여 위의 코드를 바꿔보도록 하자

type Pokemon = {
  name:string;
  level: number;
};
const pokemonArr : Pokemon[] = [{name:'이상해꽃'
                                 level:50},
                                {name:'리자몽'
                                 level:50},
                                {name:'거북왕',
                                 level;50}
                               ];
type Party= {
  pokemon : integer; //파티 포켓몬수
  hasLegendary:boolean; // 전설의 포켓몬 포함여부
};

class WeakParty{
  static MINIMUM_LEVEL_REQUIRED : number = 50; // class level에서 생성하여 instance마다 생성을 안하기때문에 메모리 소비 감소
  pokemon : number; // instance level
  constructor(pokemon:readonly Pokemon[]){
    this.pokemon = pokemon;
  }
  makeWeakParty(pokemon:number):Party{
    if(pokemon.length()<1){
      throw new Error("no pokemon to participate");
    }
    pokemon.forEach((item)=>{
      if(item.level<WeakParty.MINIMUM_LEVEL_REQUIRED){
        throw new Error("too low level");
      }
    })
    return{
      pokemon,
      hasLegendary:false
    }
  }
}


const myParty = new WeakParty(pokemonArr);
console.log(myParty.makeWeakParty);

readonly

  • const,let을 선언할 수 없는 매개 변수, class 내 변수, type내 변수를 읽기 전용으로 만들어준다.

  • 사용방법

    1. parameter

      function func(arr : readonly string[]){ 
         console.log(arr); 
      }
    2. class variable && type variable

      class myClass{ 
         readonly name : string = "bill"; // 외부에서 참조 가능하지만 수정불가능상태 
      }
      
      type myType{ 
         readonly name : string; // myType으로 정의된 데이터의 name은 참조는 가능하지만 변경이 불가능하다. 
      }

static

  • class level에서 생성되는 변수. 인스턴스가 아무리 많이 생성되어도 메모리는 한곳에만 저장되어 메모리 낭비를 줄일 수 있다.

아직 class를 도입한 코드가 더 좋다고 딱히 말할 수는 없다.

하지만 이후에 나오는 encapsulation, abstraction, inheritance, polymorphism, composition을 도입하면 확장성이 얼마나 좋아지는지 알 수 있을것이다.

+ Recent posts