본문 바로가기
JavaScript

Builder 패턴을 적용한 JS 객체 배열 (with typescript)

by 오근성 2023. 4. 6.
728x90

Enum과 string 으로 구성된 객체가 있을때 interface 를 다음과 같이 정의할 수 있다.

enum Fruit {
  APPLE = 'APPLE',
  BANANA = 'BANANA',
}

interface MyInterface {
  A: string;
  B: string;
  fruit: Fruit;
}

 

아래와 같은 방식으로 객체를 선언할 수 있다.

import { MyInterface, Fruit } from './MyInterface';

const myObject: MyInterface = {
  A: 'Hello',
  B: 'World',
  fruit: Fruit.APPLE,
};

console.log(myObject);

 

Builder 패턴을 적용하여 MyInterface 객체 배열을 생성하려면 아래와 같이 하면된다.

 

// MyInterfaceBuilder.ts
import { MyInterface, Fruit } from './MyInterface';

export class MyInterfaceBuilder {
  private instances: MyInterface[] = [];

  addInstance(A: string, B: string, fruit: Fruit): MyInterfaceBuilder {
    this.instances.push({ A, B, fruit });
    return this;
  }

  build(): MyInterface[] {
    return this.instances;
  }
}

이 클래스는 MyInterface 객체를 배열에 추가하는 addInstance 메서드와 생성된 배열을 반환하는 build 메서드를 가진다.

 

 

아래와 같은 방식으로 객체 배열을 생성할  수 있다.

// main.ts
import { MyInterfaceBuilder } from './MyInterfaceBuilder';
import { Fruit } from './MyInterface';

const builder = new MyInterfaceBuilder();

const myInterfaceArray = builder
  .addInstance('Hello', 'World', Fruit.APPLE)
  .addInstance('Example', 'String', Fruit.BANANA)
  .build();

console.log(myInterfaceArray);
728x90

댓글