>  기사  >  웹 프론트엔드  >  JavaScript 디자인 패턴 학습 Factory_javascript 기술

JavaScript 디자인 패턴 학습 Factory_javascript 기술

WBOY
WBOY원래의
2016-05-16 18:48:59805검색
코드 복사 코드는 다음과 같습니다.

/* DisplayModule 인터페이스 */
var DisplayModule. = new Interface ('DisplayModule', ['append', 'remove', 'clear'])
/* ListDisplay 클래스 */
//RSS를 표시하는 인터페이스를 통해 팩토리를 구현합니다. 목록 모드에서
var ListDisplay = function(id, parent) { // DisplayModule 구현
this.list = document.createElement('ul')
this.list.id = id
parent.appendChild(this.list)
};
ListDisplay.prototype = {
append: function(text) {
var newEl = document.createElement('li'); this.list.appendChild( newEl);
newEl.innerHTML = text;
return newEl;
},
remove: function(el) {
this.list.removeChild(el) ;
},
clear: function() {
this.list.innerHTML = '';
}
}; */
var conf = {
id: 'cnn-top-stories',
feedUrl: 'http://rss.cnn.com/rss/cnn_topstories.rss',
updateInterval: 60, // 초 단위 .
부모: $('feed-readers')
};
/* FeedReader 클래스 */
var FeedReader = function(display, xhrHandler, conf) {
this.display = 표시;
this.xhrHandler = xhrHandler;
this.startUpdates()
};
FeedReader.prototype: 함수( ) {
var that = this;
var callback = {
success: function(text, xml) { that.parseFeed(text, xml) },
failure: function(status) { that.showError(status) ; }
};
this.xhrHandler.request('GET', 'feedProxy.php?feed=' this.conf.feedUrl,
콜백); ,
parseFeed: function(responseText, responseXML) {
this.display.clear()
var items = responseXML.getElementsByTagName('item')
for(var i = 0, len = items.length; i < len i ) {
var title = items[i].getElementsByTagName('title')[0]
var link = items[i].getElementsByTagName('link' )[0];
this.display.append(''
title.firstChild.data '
')
}
},
showError: function(statusCode) {
this.display.clear();
this.display.append('피드를 가져오는 동안 오류가 발생했습니다.'); ,
stopUpdates: function() {
clearInterval(this.interval);
},
startUpdates: function() {
this.fetchFeed()
var that = this ;
this.interval(function() { that.fetchFeed(); },
this.conf.updateInterval * 1000)
}
/* FeedManager 네임스페이스 . */
//공장 관리자, 여기에서
var FeedManager = {
createFeedReader: function(conf) {
var displayModule = new ListDisplay(에 전달된 매개변수를 기반으로 특정 디스플레이를 선택할 수 있습니다. conf.id '-display' , conf.parent);
Interface.ensureImplements(displayModule, DisplayModule);
var xhrHandler = XhrManager.createXhrHandler()
Interface.ensureImplements(xhrHandler, AjaxHandler); 🎜>새 FeedReader(displayModule, xhrHandler, conf) 반환
}
}
===================== ======= =====================
또 다른 자전거 공장 예시:
var BicycleShop = function() {}; >BicycleShop.prototype = {
sellBicycle: function(model) {
var bike = this.createBicycle(model)
bicycle.assemble();
bicycle.wash(); return bike;
},
createBicycle: function(model) {
throw new Error('추상 클래스에서 지원되지 않는 작업.')
}
}; AcmeBicycleShop 클래스. */
var AcmeBicycleShop = function() {};
extend(AcmeBicycleShop, BicycleShop)
AcmeBicycleShop.prototype.createBicycle = function(model) {
var bike; switch(model) {
case 'The Speedster':
bicycle = new AcmeSpeedster();
break
case 'The Lowrider':
bicycle = new AcmeLowrider(); >break;
case 'The Flatlander':
bicycle = new AcmeFlatlander();
break;
case 'The Comfort Cruiser':
default:
bicycle = new AcmeComfortCruiser( );
}
Interface.ensureImplements(bicycle, Bicycle);
return Bicycle;
/* GeneralProductsBicycleShop 클래스 */
var GeneralProductsBicycleShop = function() ;
extend(GeneralProductsBicycleShop, BicycleShop);
GeneralProductsBicycleShop.prototype.createBicycle = function(model) {
switch(model) {
case 'The Speedster':
bicycle = new GeneralProductsSpeedster();
break;
case 'The Lowrider':
bicycle = new GeneralProductsLowrider()
break; = new GeneralProductsFlatlander() ;
break;
case 'The Comfort Cruiser':
default:
bicycle = new GeneralProductsComfortCruiser()
}
Interface.ensureImplements(자전거, 자전거 );
자전거 반납;


/* 사용법 */

코드 복사


코드는 다음과 같습니다.

var alecsCruisers = new AcmeBicycleShop();
var yourNewBike = alecsCruisers.sellBicycle('로우라이더');
var bobsCruisers = new GeneralProductsBicycleShop();
var yourSecondNewBike = bobsCruisers.sellBicycle('로우라이더');

성명:
본 글의 내용은 네티즌들의 자발적인 기여로 작성되었으며, 저작권은 원저작자에게 있습니다. 본 사이트는 이에 상응하는 법적 책임을 지지 않습니다. 표절이나 침해가 의심되는 콘텐츠를 발견한 경우 admin@php.cn으로 문의하세요.