싱글톤 패턴

wisdom·2022년 6월 28일
0

싱글톤 패턴의 장점

  1. 메모리 효율
  2. 도메인 또는 프로그램에서 인스턴스가 절대적으로 한 개만 존재한다는 것을 보증받는다.

Before

import * as express from "express"
import catsRouter from "./cats/cats.route";

const port: number = 8000;
const app: express.Express = express()

app.use((req: express.Request, res: express.Response, next: any) => {
    console.log(req.rawHeaders[1]);
    console.log('this is logging middleware');
    next();
});

app.use(express.json());
app.use(catsRouter);


app.use((req:express.Request, res:express.Response) => {
    console.log('this is error middleware');
    res.send({error: '404 not found error'});
})

app.listen(port, () => {
    console.log(`Example app listening on port ${port}`)
})

After

import * as express from "express"
import catsRouter from "./cats/cats.route";

const port: number = 8000;

class Server {
    public app: express.Application;

    constructor() {
        const app: express.Application = express();
        this.app = app;
    }

    private setRoute() {
        this.app.use(catsRouter);
    }

    private setMiddleware() {
        this.app.use((req: express.Request, res: express.Response, next: any) => {
            console.log(req.rawHeaders[1]);
            console.log('this is logging middleware');
            next();
        });

        this.app.use(express.json());
        this.setRoute();

        this.app.use((req:express.Request, res:express.Response) => {
            console.log('this is error middleware');
            res.send({error: '404 not found error'});
        })
    }

    public listen() {
        this.setMiddleware();
        this.app.listen(port, () => {
            console.log(`Example app listening on port ${port}`)
        })
    }
}

function init() {
    const server = new Server();
    server.listen();
}

init();
  • Server 라는 클래스를 만들었고 그 클래스는 단 하나의 인스턴스를 만들었다. 그리고 이 인스턴스는 고유하다는 것을 보증받는다!
    - 서버 인스턴스가 프로그램에서 한 번만 사용되어야 하기 때문이다.
    • 여러 서버를 여는 것이 아닌 게 확실하기에 서버 인스턴스는 하나만 필요하다.
    • 다수의 Server 인스턴스를 찍어서 사용하는 것은 복잡함을 야기시키고 불필요하다.

✅ 하나의 인스턴스만을 찍어내고 사용하는 것이 바로 싱글톤 패턴이다.

node.js 에서는 싱글톤 패턴이 의미가 없을까?

  • 구글링을 하다가 오래된 글이긴 하지만 아래 링크를 보게 되었다.
    - https://stackoverflow.com/questions/13179109/singleton-pattern-in-nodejs-is-it-needed
  • 의미가 없다고 주장하는 사람들의 의견은 예를들어 아래 코드를 여러번 찍어도 캐싱이 되기 때문에 모듈을 import 하는 관점에서는 의미가 없다는 것이 아닐까?
    import * as express from "express"; 
  • 자바를 공부할 때 싱글톤 패턴의 중요성을 배웠던 걸로 기억한다. 분명 소프트웨어 코드 작성에 있어 의미가 있다.
  • 설령 메모리 효율에 있어서 장점이 없다 해도, 코드 디자인 측면에서 장점이 있다면 의미가 있다고 생각한다.

싱글톤 패턴은 항상 좋을까?

결론

  • 싱글톤 패턴을 항상 분명한 경우에만 적용해야 한다. 서버 실행과 같이 딱 한 번 사용됨을 보증받아야 하는 경우가 바로 위에서 말한 분명한 경우다.
profile
문제를 정의하고, 문제를 해결하는

0개의 댓글