반응형

service나 module은 기보적으로 싱글턴으로 작동한다.

하지만 여기서는 클래스 단위의 싱글턴을 사용할 것이다.

 

시간을 yyyyMMdd패턴으로 바꾸어주는 클래스를 예시로 들어보겠다.

namespace 와 export 키워드를 반드시 사용한다.

// date-formatter.ts

export namespace DateFormatterSingleton {  

    export function nowYYYYmmDD():string {
        let _temp = new Date();
        return _yyyyMMdd(_temp);
    }

    export function toYYYYmmDD(date: string):string {
        let _temp = new Date(date);
        return _yyyyMMdd(_temp);
    }

    function _yyyyMMdd(date: Date) {
        return date.getFullYear()+'-'
        +_toTwoDigits((date.getMonth()+1).toString())+'-'
        +_toTwoDigits(date.getDate().toString());
    }

    function _toTwoDigits(numeric: string):string {
        return numeric.length == 1 ? "0"+numeric : numeric;
    }
}

 

사용방법

import { DateFormatterSingleton } from 'src/app/model/date-formatter';

datePicker: string = DateFormatterSingleton.nowYYYYmmDD();

위 코드와 같이 사용하면된다. Java에서와 같이 getInstance()와 같은 호출은 필요없다.

반응형

+ Recent posts