상세 컨텐츠

본문 제목

Javascript Pattern 정리

Develop/JS

by 웽디 2017. 8. 28. 16:30

본문

네임스페이스 패턴

전역 변수의 개수를 줄여준다.

var wendy= wendy|| {};
 
wendy.Parent = function () {};
wendy.Child = function() {};
 
wendy.modules = {};
wendy.modules.slider = {};
(+)모듈을 추가
cs

모듈 패턴

wendy.modules.slider = (function() {
     var nPage = '4';
 
     return {
          getPageCount: function() {
               return nPage;
          }
     };
 
});
 
wendy.modules.slider = (function() {
     var nPage = '4',
 
     getPageCount = function() {
          return nPage;
     }
 
     return {
          getPageCount: getPageCount
     };
 
});
cs

싱글톤 패턴

객체의 인스턴스를 하나로 유지시킨다.

var Person;
 
(function() {
     var instance;
 
     Person = function Person() {
          if(instance) {
               return instance;
          }
 
          instance = this;
 
          this.name = 'wendy';
     };
 
}());
 
var a = new Person(); //b.name = wendy
var b = new Person(); //b.name = wendy
=== b; //true
cs

팩토리 패턴

var car1 = CarFactory.factory('car1');
var car2 = CarFactory.factory('car2');
 
function CarFactory() {};
 
CarFactory.prototype.drive = function() {
     console.log(this.doors);
};
 
CarFactory.factory = function (type) {
     if (typeof CarFactory[type] !== 'function') {
          throw { name'error', message: '없음' };
     }
 
     if (typeof CarFactory[type].prototype.drive !== 'function') {
          CarFactory[type].prototype = new CarFactory();
     }
 
     newCar = new CarFactory[type]();
 
     return newCar;
};
 
CarFactory.car1 = function() { this.doors = 4; }
CarFactory.car2 = function() { this.doors = 8; }
 
car1.drive(); //4
car2.drive(); //8
cs

(+) Object도 내부적으로 팩토리 패턴을 사용한다.

Object는 내부적으로 Number() 생성자를 만든다. 문자열이나 불린 값 또한 동일하게 적용된다. 입력 값이 없거나 다른 값을 전달하면 일반적인 객체를 생성한다.

var obj = new Object(),
    number = new Object(1),
    string = new Object('1'),
    boolean = new Object(true);
 
obj.constructor === Object//true
number.constructor === Number//true
string.constructor === String//true
boolean.constructor === Boolean//true
cs

데코레이터(장식자) 패턴

런타임 시에 객체에 기능을 추가한다

function Sale(price) {
     this.price = price || 1000;
     this.decoratorList = [];
}
 
Sale.decorators = {};
Sale.decorators.fedtax = {
     getPrice: function(price) {
          return price + 100;
     }
};
 
Sale.prototype.decorate = function (decorator) {
     this.decoratorList.push(decorator);
};
 
Sale.prototype.getPrice = function() {
     var price = this.price,
         index, max = this.decoratorList.lengthname;
 
     for(index = 0; index < max; index++) {
          name = this.decoratorList[index];
          price = Sale.decorators[name].getPrice(price);
     }
     return price;
};
 
var sale = new Sale(1000);
sale.decorate('fedtax');
sale.getPrice(); // 1100
cs

퍼사드 패턴

객체의 대체 인터페이스를 제공한다. 두개 이상의 메서드가 함께 호출되는 경우가 있다면, 이런 메서드를 하나로 묶어주는 새로운 메서드를 만드는 게 좋다.

var myEvent = {
     stopfunction (e) {
          if(typeof e.preventDefault === 'function') {
               e.preventDefault();
          }
 
          if(typeof e.stopPropagation === 'function') {
               e.stopPropagation();
          }
 
          if(typeof e.cancelBubble === 'boolean') {
               e.cancelBubble = true;
          }
     }
};
cs

프록시 패턴

비용이 큰 작업을 줄이기 위해 작업들을 하나로 묶거나, 정말 필요할 때만 실행하게 해준다. 실제 대상 객체를 보호하여 되도록 일을 적게 시킨다. 프록시는 초기화 요청을 받지만, 실제 대상 객체가 정말로 사용되기 전까지는 이 요청을 전달하지 않는다. makeRequest를 여러번 요청하는 경우, Proxy에서 한번만 실제 HTTP객체한테는 한번만 전송할 수 있도록 이전 처리를 한 후, 전달한다. Proxy에서 캐시를 해두고, 동일한 ID에 대한 정보를 요청하면, 캐시된 결과를 반환해주는 역할도 할 수 있다.

중재자 패턴

객체간의 통신은 유지보수가 쉽고, 다른 객체를 건들지 않으면서 안전하게 관리되어야 한다. 동료 객체들이 직접 통신하지 않고, 중재자 객체를 거친다. 자신의 상태가 변경되면 중재자에게 알리고, 중재자는 변경사항을 알아야 하는 다른 동료 객체들에게 알린다.

감시자 패턴

감시 가능한 객체들을 만들어 결합도를 낮춘다. 특정 이벤트를 감시하고 있는 모든 감시자들에게 그 이벤트가 발생했을 때 알려준다.


'Develop > JS' 카테고리의 다른 글

[JQuery] document, window  (0) 2016.01.04

관련글 더보기

댓글 영역