250x250
Notice
Recent Posts
Recent Comments
Link
«   2025/10   »
1 2 3 4
5 6 7 8 9 10 11
12 13 14 15 16 17 18
19 20 21 22 23 24 25
26 27 28 29 30 31
Archives
Today
Total
관리 메뉴

devlog_owen

231221 [TIL] 타입스크립트 디자인패턴 본문

TIL

231221 [TIL] 타입스크립트 디자인패턴

developer_owen 2023. 12. 22. 02:13
728x90

1. 추상화 팩토리 예시코드

// Creational Patterns-Abstract Factory
interface FruitsFarm {
  createJam(): Jam;
  createJuice(): Juice;
}

// Concrete Factory 1
class MandarinFarm implements FruitsFarm {
  createJam(): Jam {
    return new MandarinJam();
  }
  createJuice(): Juice {
    return new MandarinJuice();
  }
}

// Concrete Factory 2
class StrawberryFarm implements FruitsFarm {
  createJam(): Jam {
    return new StrawberryJam();
  }
  createJuice(): Juice {
    return new StrawberryJuice();
  }
}

// Abstract Product
interface Jam {}
interface Juice {}

// Concrete Product 1
class MandarinJam implements Jam {}
class MandarinJuice implements Juice {}

// Concrete Product 2
class StrawberryJam implements Jam {}
class StrawberryJuice implements Juice {}

//usage
function produceProducts(factory: FruitsFarm) {
  const jam = factory.createJam();
  const juice = factory.createJuice();

  console.log('Produced:', jam, juice);
}

const mandarinFactory = new MandarinFarm();
const strawberryFactory = new StrawberryFarm();

console.log('귤 생산품이 생산되고 있습니다...');
produceProducts(mandarinFactory);

console.log('딸기 생산품이 생산되고 있습니다...');
produceProducts(strawberryFactory);

 

 

 

 

 

 

 

 

2. 데코레이터 예시코드

//Structural Patterns-Decorator
//component
interface Salad {
  cost(): number;
  description(): string;
}

// Concrete Component
class SimpleSalad implements Salad {
  cost() {
    return 6000;
  }
  description() {
    return '기본 샐러드';
  }
}

// Decorator
abstract class saladDecorator implements Salad {
  protected salad: Salad;

  constructor(salad: Salad) {
    this.salad = salad;
  }
  cost() {
    return this.salad.cost();
  }

  description() {
    return this.salad.description();
  }
}

// Concrete Decorators
class ChickenSalad extends saladDecorator {
    cost() {
        return this.salad.cost()+3000
    }
    description() {
        return this.salad.description()+'+ 치킨'
    }
}


class BeefSalad extends saladDecorator {
    cost() {
        return this.salad.cost()+4000
    }
    description() {
        return this.salad.description()+'+ 비프'
    }
}

//usage
const simpleSalad = new SimpleSalad()
console.log(simpleSalad.description(),'가격:',simpleSalad.cost())

const chickenSalad = new ChickenSalad(simpleSalad)
console.log(chickenSalad.description(),'가격:',chickenSalad.cost())

const beefSalad = new BeefSalad(simpleSalad)
console.log(beefSalad.description(),'가격:',beefSalad.cost())

 

 

 

 

3. 옵저버 예시코드

//Behavioral Patterns-Observer 
// Subject 
interface ComicBook {
  subscribe(subscriber: Otaku): void;
  unsubscribe(subscriber: Otaku): void;
  notifyLatestIssue(): void;
}

// Concrete Subject
class WeeklyShonenJump implements ComicBook {
  private subscribers: Otaku[] = [];
  private latestIssue: string = '';

  subscribe(subscriber: Otaku) {
    this.subscribers.push(subscriber);
  }

  unsubscribe(subscriber: Otaku) {
    this.subscribers = this.subscribers.filter(sub => sub !== subscriber);
  }

  publishIssue(issue: string) {
    this.latestIssue = issue;
    this.notifyLatestIssue();
  }

  notifyLatestIssue() {
    this.subscribers.forEach(subscriber => subscriber.update(this.latestIssue));
  }
}

// Observer 
interface Otaku {
  update(issue: string): void;
}

// Concrete Observer 
class OtakuFan implements Otaku {
  private name: string;

  constructor(name: string) {
    this.name = name;
  }

  update(issue: string) {
    console.log(`${this.name}님이 주간 소년점프 ${issue} 최신호를 받으셨습니다.`);
  }
}


// Usage
const jumpMagazine = new WeeklyShonenJump();

const fan1 = new OtakuFan('나루토');
const fan2 = new OtakuFan('사스케');

jumpMagazine.subscribe(fan1);
jumpMagazine.subscribe(fan2);

jumpMagazine.publishIssue('Volume 78');
728x90