studye / typescript

타입스크립트는 자바스크립트랑 다른 언어인가요?
7 stars 0 forks source link

[Chapter3] Factory Design Pattern #14

Open jongmoon opened 7 years ago

jongmoon commented 7 years ago

What the Factory Design Pattern does

정보에 기반하여 몇개의 클래스 중 매칭되는 인스턴스 생성

enum PersonCategory {
  Infant,
  Child,
  Adult
}

interface IPerson {
  Category: PersonCategory,
  canSignContracts(): boolean;
  printDetails();
}

abstract class Person implements IPerson {
  Category: PersonCategory;
  private DateOfBirth: Date;// Person 에서만 접근가능

  constructor(dateOfBirth: Date) {
    this.DateOfBirth = dateOfBirth;
  }

  abstract canSignContracts(): boolean;// abstract 이므로 반드시 구현 필요

  // 상속받는 어떤 클래스라도 아래 함수 사용 가능 
  printDetails(): void {
    console.log(`Person: `);
    console.log(`Date of Birth: ` + `${this.DateOfBirth.toDateString()}`);
    console.log(`Category: ` + `${PersonCategory[this.Category]}`);
    console.log(`Can sign:` + `${this.canSignContracts()}`);
  }
}

Specialist Classes

class Infant extends Person {
  constructor(dateOfBirth: Date) {
    super(dateOfBirth);
    this.Category = PersonCategory.Infant;
  }
  canSignContracts(): boolean {
    return false;
  }
}

class Child extends Person {
  constructor(dateOfBirth: Date) {
    super(dateOfBirth);
    this.Category = PersonCategory.Child;
  }
  canSignContracts(): boolean {
    return false;
  }
}

class Adult extends Person {
  constructor(dateOfBirth: Date) {
    super(dateOfBirth);
    this.Category = PersonCategory.Adult;
  }
  canSignContracts(): boolean {
    return true;
  }
}

Factory Class

class PersonFactory {
  getPerson(dateOfBirth: Date) {
    let dateNow = new Date();
    let currentMonth = dateNow.getMonth() + 1;
    let currentDate = dateNow.getDate();

    let dateTwoYearsAgo = new Date(dateNow.getFullYear() - 2, currentMonth, currentDate);
    let date18YearsAgo = new Date(dateNow.getFullYear() - 18, currentMonth, currentDate);

    if (dateOfBirth >= dateTwoYearsAgo) {
      return new Infant(dateOfBirth);
    } else if (dateOfBirth >= date18YearsAgo) {
      return new Child(dateOfBirth);
    } else {
      return new Adult(dateOfBirth);
    }
  }
}

Using the Factory class

let factory = new PersonFactory();
let p1 = factory.getPerson(new Date(2015, 0, 20));
p1.printDetails();

let p2 = factory.getPerson(new Date(2000, 0, 20));
p2.printDetails();

let p3 = factory.getPerson(new Date(1969, 0, 20));
p3.printDetails();
jongmoon commented 7 years ago

근데 잘 안됨 ㅜㅜ

[ts] Class 'Person' incorrectly implements interface 'IPerson'. Property 'canSigncontracts' is missing in type 'Person'. class Person

denzels commented 7 years ago

@jongmoon 잘 안된거 본문 코드 수정했남?

jongmoon commented 7 years ago

@denzels 옙!