Javascript - DeepDive (14) : 자바스크립트 패턴

­이승환·2021년 11월 27일
0

Javascript DeepDive

목록 보기
13/13

소개


Javascript Patterns 7장 디자인 패턴 요약본입니다. 이번 포스팅의 경우 아키텍쳐 패턴이라기 보단, 자바스크립트에서 함수를 만드는 것에 있어서 디자인 패턴이라고 이해하면 좋을 것 같다. views의 비지니스 로직을 담아 놓은 controller나 store에서 메서드를 디자인 하는것에 참고하면 좋을 것 같다.

싱글톤 패턴

  • 특정 클래스의 객체를 한개만 유지하는 패턴
  • 자바스크립트는 이미 객체 리터럴을 이용한 객체 생성방법이 싱글톤과 유사하다고 한다
var obj = {
  myprop : "my value"
};

var obj2 = {
  myprop : "my value"
};
obj === obj2; // false
obj == obj2;  // false

팩토리 패턴

  • 비슷한 객체를 공장에서 찍어내듯이 반복적으로 생성할 수 있게하는 패턴
  • 컴파일 시점에 구체적인 타입을 몰라도 객체 생성이 가능하다
  • 가장 흔한 사례는 Object()를 이용한 객체 생성시, 주어지는 값의 타입에 따라 String, Boolean.. 등 타입을 정해서 객체 생성한다
// 팩토리 패턴 구현 예제
function CarMaker() {}
CarMaker.prototype.drive = function () {
  return "Vroom, I have " + this.doors + "doors";
};
CarMaker.factory = function (type) {
  var constr = type,
      newcar;

  // 생성자 존재하지 않으면 에러발생
  if (typeof CarMaker[constr] !== "function") {
    throw {
      name: "Error",
      message: constr + "doesn't exist"
    };
  }

  // 생성자 존재 확인 후 부모 상속
  if (typeof CarMaker[constr].prototype.drive !== "function") {
    CarMaker[constr].prototype = new CarMaker();
  }

  newcar = new CarMaker[constr]();

  return newcar;
};

CarMaker.Compact = function () {
  this.doors = 4;
};
CarMaker.Convertible = function () {
  this.doors = 2;
};
CarMaker.SUV = function () {
  this.doors = 24;
};
// --

// 위 패턴을 이용한 결과
var corolla = CarMaker.factory("Compact");
var solstice = CarMaker.factory("Convertible");
corolla.drive();  // "Vroom, I have 4 doors"
solstice.drive(); // "Vroom, I have 2 doors"

Iterator 패턴

  • 객체의 내부구조가 복잡하더라도 개별 속성에 쉽게 접근하기 위한 패턴
  • 렉시컬 환경, 클로저를 이용해서 작성하는 경우가 많으나, 차라리 ES2015 이후에는 Map, Set, WeakMap, WeakSet 등을 활용해도 좋을 것으로 보임
var agg = (function () {
  var index = 0,
      data = [1, 2, 3, 4, 5],
      length = data.length;

  return {
    next : function () {
      var element;
      if (!this.hasNext()) {
        return null;
      }
      element = data[index];
      index += 1;
      return element;
    },
    hasNext : function () {
      return index < length;
    },
    rewind: function () {
      index = 0;
    },
    current: function () {
      return data[index];
    }
  };
}());

Decorator 패턴

  • 런타임시에 객체가 동적으로 부가기능을 추가할 수 있는 패턴
  • class 의 경우 constructor, prototype, __proto__ 등의 속성이 존재하는데 이것을 활용한 패턴
  • Javascript Convention에서는 별로 추천하지 않는 패턴
function Sale(price) {
  this.price = price || 100;
}
Sale.prototype.getPrice = function () {
  return this.price;
};

Sale.decorators = {};
Sale.decorators.fedtax = {
  getPrice: function () {
    var price = this.uber.getPrice(); // uber 는 상속된 객체
    price += price * 5 / 100; // 5% 세율 추가

    return price;
  }
};
Sale.decorators.money = {
  getPrice: function () {
    return "$" + this.uber.getPrice().toFixed(2);
  }
};

Proxy 패턴

  • Lazy Initialization 으로 어플리케이션의 부하를 줄여준다
var proxy = {
    ids : [],
    delay: 50,
    timeout: null,
    callback: null,
    context: null,

    makeRequest: function (id, callback, context) {
      this.ids.push(id);

      this.callback = callback;
      this.context = context;

      if (!this.timeout) {
        this.timeout = setTimeout(function () {
          proxy.flush();
        }, this.delay);
      }
    },
    flush: function () {
      http.makeRequest(this.ids, "proxy.handler:");
      this.timeout = null;
      this.ids = [];
    },
    handler: function (data) {
      var i, max;
      if (parseInt(data.query.count, 10) === 1) {
        proxy.callback.call(proxy.context, data.query.results.Video);
        return;
      }

      for (i = 0, max = data.query.results.Video.length;
            i < max; i += 1) {
        proxy.callback.call(proxy.context, data.query.results.Video[i]);
      }
    }
};
  • HTTP 요청이 50미리세컨 이내로 일어난다면, 각각 보낼 것이 아니라 setTimeout() 을 이용해서 보류 한 후에 한번에 보낸다.

Mediator 패턴

  • 객체간에 영향도(결합도) 가 높은 상태에서는 리팩토링이 예기치 않은 결과를보여줌
  • 결합도를 낮추기 위해서 객체의 상태가 변경되면 Mediator에게 먼저 전달하고 이를 Mediator가 다른 객체에 전달하는 방식의 코딩을 진행

Observer 패턴

  • 클라이언트 측 자바스크립트 프로그래밍에서 널리 사용된다
  • pub/sub 패턴이라고도 불린다
  • 이 패턴의 주요목적은 객체간의 결합도를 낮추는 것이다.
profile
Mechanical & Computer Science

0개의 댓글