본문 바로가기
Design Pattern/Structural Design

[Design Pattern] (Structural) 프록시 패턴(Proxy Pattern)

by song.ift 2023. 3. 27.

디자인 패턴 유형

  • Creation Design Pattern
    • 객체의 생성에 관련된 패턴
    • 객체의 생성 로직을 숨김으로써 유연성을 향상시킨다.
  • Strutural Design Pattern
    • 클래스와 객체의 구성에 관련된 패턴
  • Behavioral Design Pattern
    • 객체와 객체 간의 통신에 관련된 패턴

 

[Structural Design Pattern] 프록시 패턴(Proxy Pattern)

Lazy Initialization (게으른 초기화) 로 어플리케이션의 부하를 줄여준다.

javascript
닫기
var $ = function(id) { return document.getElementById(id); } $('vids').onclick = function(e) { ​​var src, id; ​​ ​​e = e || window.event; ​​src = e.target || e.srcElement; ​​ ​​if (srec.nodeName !== 'A') { ‌​​return; ​​} ​​ ​​if (type of e.preventDefault() === 'function') { ‌​​e.preventDefault(); ​​} ​​ ​​e.returnValue = false; ​​id = src.href.split('--')[1]; ​​ ​​if (src.className === 'play') { ‌​​src.parentNode.innerHTML = videos.getPlayer(id); ​​​​return; ​​} ​​ ​​src.parentNode.id = 'v' + id; ​​videos.getInfo(id); };

위와 같이 클릭 이벤트에 대해서 이벤트 핸들링이 가능하다.
아래는 Proxy 를 이용하여 HTTP 라운드 트립을 줄일 수 있는 코드이다.

javascript
닫기
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()을 이용하여 요청을 잠시 보류한 후 한번에 보낸다.
그렇게 되면 HTTP의 라운드 트립 횟수가 줄어들기 때문에 전체적으로 성능이 향상될 수 있다.

댓글