본문 바로가기
개발공부 일지/면접

Template Method(템플릿 메서드) 패턴

by Box Cat 2023. 10. 9.
728x90
반응형

Template 패턴어떤 기능을 구성하는 각 실행 순서(단계)를 미리 정하고 각 실행 단계에 대한 구체적인 코드를 재정의 할 수 있는 유연성을 제공합니다.

 

Template Method는 상속(Inheritance)을 기반으로 한다. 이를 통해 하위 클래스에서 해당부분을 확장하여 알고리즘의 일부를 변경할 수 있다. Strategy은 구성(Composition)을 기반으로 한다. 해당 동작에 해당하는 다른 전략을 제공하여 객체 동작의 일부를 변경할 수 있다. 

Template Method는 클래스 레벨에서 작동하므로 정적이다. Strategy은 객체 레벨에서 동작하므로 런타임에 동작을 전환할 수 있다.

 

 

export class AbstractClass {
  public method1(): void {
      throw new Error("Abstract Method");
  }

  public method2(): void {
      throw new Error("Abstract Method");
  }

  public method3(): void {
      throw new Error("Abstract Method");
  }

  public templateMethod(): void {
      console.log("templateMethod is being called");
      this.method1();
      this.method2();
      this.method3();
  }
}

export class ConcreteClass1 extends AbstractClass {
  public method1(): void {
      console.log("method1 of ConcreteClass1");
  }

  public method2(): void {
      console.log("method2 of ConcreteClass1");
  }

  public method3(): void {
      console.log("method3 of ConcreteClass1");
  }
}

export class ConcreteClass2 extends AbstractClass {
  public method1(): void {
      console.log("method1 of ConcreteClass2");
  }

  public method2(): void {
      console.log("method2 of ConcreteClass2");
  }

  public method3(): void {
      console.log("method3 of ConcreteClass2");
  }
}

export function show() : void {
  var c1: ConcreteClass1 = new ConcreteClass1(),
   c2: ConcreteClass2 = new ConcreteClass2();
 
  c1.templateMethod();
  c2.templateMethod();
 
 }
 show();
 
728x90
반응형

'개발공부 일지 > 면접' 카테고리의 다른 글

프론트 엔드 면접 예상문제(찐)  (0) 2023.10.12
Observer(옵저버) 패턴  (0) 2023.10.09
Command(커맨드) 패턴  (0) 2023.10.08
Iterator(이터레이터) 디자인 패턴  (0) 2023.10.08
MVC vs MVP vs MVVM  (0) 2023.10.04

댓글