[TS] Chapter 5. Typescript 컴파일러 및 구성-클래스 & 인터페이스_클래스 심화

변진상·2023년 5월 30일
0

Typescript 학습

목록 보기
8/13

목표: class의 심화 내용에 대해 학습한다.

(class의 상속, protected, getter, setter, static method와 property, abstract class, singleton에 대한 내용을 학습한다.

상속

기존에 존재하는 class의 특정 기능을 상속받고 새로운 class에 고유한 특성을 추가할 수 있다.

class IT extends Department {
  private admins: string[];

  constructor(id: string) {
    super(id, "ITdepartment"); // 상속받은 부모 class의 constructor를 실행한다.
    this.admins = [];
  }

  addAdmin(admin: string) {
    this.admins.push(admin);
  }

  displayAdmins() {
    console.log(this.admins);
  }
}

protected 접근제어자

protected 접근제어자는 private과 비슷하지만, private은 특정 class를 상속받은 자식 class에서 부모 class에서 정의한 private 변수를 변경할 수 없다. protected는 클래스 외부에서는 접근할 수 없게 막지만 상속받은 class에서 그 데이터에 접근할 수 있다.

getter vs setter

  • getter의 경우 private 변수를 메서드를 통해 접근해 값을 가져오는 것이 아니라. object.property와 같이 기존에 object의 property에 .(dot)을 이용해 값에 접근할 수 있게 해줍니다.

  • setter도 마찬가지로 점으로 접근가능하고 대입 연산자를 통해 값을 바꿀 수 있고 그 값을 class 내의 다른 메소드를 사용해 값을 변화시킬 수 있습니다.

  • getter

get getAdmins() {
    if (this.admins) {
      return this.admins;
    }

    throw new Error("등록된 admin이 없습니다.");
  }

...

console.log(ITTeam.getAdmins);
  • setter
  set setAdmin(value: string) {
    if (!value) {
      throw new Error("적절하지 않은 value입니다.");
    }

    this.addAdmin(value);
  }

...


ITTeam.setAdmin = "진상";
ITTeam.setAdmin = "수달";
ITTeam.setAdmin = "김밥";

정적(static) 메서드 & 속성

정적메서드와 속성을 사용하여, 인스턴스에서 접근할 수 없는 속성과 메소드를 클래스에서 추가할 수 있다. 기존에 접근 가능했던 instanceName.methodOrProp() 이런식의 접근은 인스턴스 메소드의 접근 방식이다. 반면 정적 메서드나 속성은 new className과 같이 인스턴스를 따로 만들어서 접근하지 않아도 된다. className.methodorProp() 이런식으로 직접 클래스 자체에 속성과 메서드에 접근해야한다. 이 때의 className은 그루핑 매카니즘의 네임스페이스와 같은 역할을 한다.

static 메서드나 속성을 this로 접근하려고 하면 에러를 띄우는데 this는 인스턴스를 참조하기 때문이다.

// static property 초기화
static companyName = "otterCompany";
// static method 초기화
static makeOtterWithName(name: string) {
  if (!name) {
    throw new Error("there is no otter's name!");
  }

  return `New Otter's name is ${name}!`;
}

// static property
console.log(Department.companyName);

// static method
console.log(Department.makeOtterWithName("진상"));

추상(abstract) class, method

  • 추상 클래스: 상속을 위한 클래스로 하나 이상의 추상 메서드를 포함한다.
  • 추상 메서드: 추상 클래스 내에 형식(parameter와 return type)에 대한 명세와 구조만 존재하고 구체적인 구현은 상속받은 클래스 내에서 한다.

OOP의 핵심 개념 중 하나인 abstraction을 실현할 수 있는 키워드라고 볼 수 있다. 추상화의 경우 복잡성을 최소화해 상위 클래스에서 하위 클래스를 거쳐가며 세부사항을 구체화해갑니다. OOP에서는 두 가지의 클래스가 있는데, 추상 클래스(abstract class)와 구상클래스(concrete class)다. 추상 클래스가 상위 클래스, 구상 클래스가 하위 클래스라고 할 수 있다.

abstract class Animal {
  constructor(protected name: string, protected sound: string) {}
	// 상속받은 class에서 부모 클래스의 property인 name과 sound에
  	// 접근 할 수 있도록 protected 접근 제어자를 사용한다.
  abstract whatYourName(): void;
}

class Dog extends Animal {
  constructor(name: string) {
    super(name, "멍멍!");
  }

  whatYourName(): void {
    console.log(this.name);
  }

  whatYourSound(): void {
    console.log(this.sound);
  }
}

const dog = new Dog("바둑");

dog.whatYourName(); // => 바둑
dog.whatYourSound(); // => 멍멍!

싱글톤 패턴 - private 생성자

싱글톤 패턴: OOP의 개념 중 하나로, 특정 클래스의 인스턴스를 정확히 하나만 갖도록 한다. 이 패턴은 정적 메소드나 속성을 사용할수 없거나 사용하지 않고자하는 동시에 클래스 기반으로 여러 객체를 만들 수는 없지만 항상 클래스를 기반으로 정확히 하나의 객체만 가질 수 있도록 하고자 하는 경우 유용하다.

구현 방법

  1. private constructor 구현
  2. class 내에 instance static private property 구현
  3. getInstance(this.instance가 존재하면 return, 존재하지 않으면 new ClassName으로 instance sgtatic preivate property에 인스턴스 생성 후 할당하고 return)
class Human {
  constructor(protected name: string, protected age: number) {}
}

class Zzheck extends Human {
  private static instance: Zzheck;
  private constructor(name: string, age: number) {
    super(name, age);
  }

  static getZzheck() {
    if (Zzheck.instance) {
      return this.instance;
    }
    this.instance = new Zzheck("짹짹", 23);
    return this.instance;
  }
}

const zz1 = Zzheck.getZzheck();
const zz2 = Zzheck.getZzheck();

console.log(zz1, zz2, "is same! just one Instance!");
profile
자신을 개발하는 개발자!

0개의 댓글