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();
What the Factory Design Pattern does
정보에 기반하여 몇개의 클래스 중 매칭되는 인스턴스 생성
Specialist Classes
Factory Class
Using the Factory class