{
type CoffeeCup = {
shots: number;
hasMilk: boolean;
};
*// interface*
interface CoffeeMakerA {
makeCoffee(shots: number): CoffeeCup;
}
*// Parent Class*
class CoffeeMaker {
private static BEANS_GRANS_PER_SHOT = 7;
private coffeeBeans: number = 0;
constructor(coffeeBeans: number) {
this.coffeeBeans = coffeeBeans;
}
private grindBeans(shots: number) {
console.log(`grinding beans for ${shots}`);
if (this.coffeeBeans < shots * CoffeeMaker.BEANS_GRANS_PER_SHOT) {
throw new Error('Not enough coffee beans!');
}
this.coffeeBeans -= shots * CoffeeMaker.BEANS_GRANS_PER_SHOT;
}
private preheat(): void {
console.log('heating up...π₯');
}
private extract(shots: number): CoffeeCup {
console.log(`Pulling ${shots} shots...β`);
return {
shots: shots,
hasMilk: false,
}
}
public makeCoffee(shots: number): CoffeeCup {
this.grindBeans(shots);
this.preheat();
return this.extract(shots);
}
public clean() {
console.log("Coffee Cleaning~...β¨");
}
}
*// Child Class - 01
// λ€νμ± 1*
class CaffeLatteMachine extends CoffeeMaker {
constructor(coffeeBeans: number, public serialNumber: string) {
super(coffeeBeans);
}
private steamMilk(): void {
console.log('Steaming some milk... π₯');
}
public makeCoffee(shots: number): CoffeeCup { *// μ€λ²λΌμ΄λ© λμ΄ νΈμΆλλ€.*
const coffee = super.makeCoffee(shots);
this.steamMilk();
console.log(coffee);
return {
...coffee,
hasMilk: true,
}
}
}
*// Child Class - 02
// λ€νμ± 2*
class SweetCoffeeMaker extends CoffeeMaker {
public makeCoffee(shots: number): CoffeeCup {
const coffee = super.makeCoffee(shots);
console.log('sugar...');
return {
...coffee,
hasSugar: true,
}
}
}
const machines = [
new CoffeeMaker(24),
new CoffeeLatteMachine(24, 'ssss-1'),
new SweetCoffeeMaker(24),
new CoffeeMaker(24),
new CoffeeLatteMachine(24, 'ssss-2'),
new SweetCoffeeMaker(24),
];
machines.forEach(machine => {
console.log('----------------------');
machine.makeCoffee(1);
});
}
[ λ€νμ± - polymorphism ]
νλμ μΈν°νμ΄μ€λ λΆλͺ¨ ν΄λμ€λ₯Ό μμν 'μμ ν΄λμ€λ€' μ΄ μΈν°νμ΄μ€μ λΆλͺ¨ ν΄λμ€μ μλ ν¨μλ€μ λ€λ₯Έ λ°©μμΌλ‘ λ€μνκ² κ΅¬μ± ν¨μΌλ‘μ μ‘°κΈ λ λ€νμ±μ λ§λ€ μ μλ κ²μ λ§νλ€.
κ·Έλ¦¬κ³ μΈν°νμ΄μ€μ λΆλͺ¨ ν΄λμ€μλ 'λμΌν ν¨μ'λ₯Ό ν΅ν΄μ κ°κ°μ ꡬνλ μμ ν΄λμ€ λ΄λΆ ꡬν μ¬νμ μ κ²½μ°μ§ μκ³ μ½μλ ν κ°μ§μ ν¨μAPIλ₯Ό νΈμΆ ν¨μΌλ‘μ μ¬μ©νλ μ¬λλ κ°νΈνκ² λ€μν κΈ°λ₯λ€μ νμ©ν μ μλλ‘ λμμ€λ€.