@EncyKe
2017-03-10T03:43:44.000000Z
字数 17097
阅读 1428
#读书
/**
* @module
* @description 构造模式示例:汽车构造器
* @example
* var mondeo = new Car('Ford Mondeo', 2010, 5000);
* mondeo.toString();
*/
function Car(model, year, miles) {
// 公有属性:由 this 暴露
this.model = model;
this.year = year;
this.miles = miles;
// 私有属性
var action = ' has done ';
var unit = ' miles.';
// 公有方法
this.toString = function (){
return this.model + action + this.miles + unit;
};
}
/**
* @module
* @description 构造模式示例:汽车构造器
* @example
* var mondeo = new Car('Ford Mondeo', 2010, 5000);
* mondeo.toString();
*/
function Car(model, year, miles) {
// 公有属性:由 this 暴露
this.model = model;
this.year = year;
this.miles = miles;
// 私有属性
var action = ' has done ';
var unit = ' miles.';
// 公有方法
Car.prototype.toString = function (){
return this.model + action + this.miles + unit;
};
}
或者——
/**
* @module
* @description 构造模式示例:汽车构造器
* @example
* var mondeo = new Car('Ford Mondeo', 2010, 5000);
* mondeo.toString();
*/
function Car(model, year, miles) {
// 公有属性:由 this 暴露
this.model = model;
this.year = year;
this.miles = miles;
// 私有属性
var action = ' has done ';
var unit = ' miles.';
// 公有方法
Car.prototype = {
wheels: 4,
toString: function () {
return this.model + action + this.miles + unit;
}
};
}
/**
* @module
* @description 原型模式示例:汽车构造器
* @example
* var mondeo = new Car();
* mondeo.name = 'Ford Mondeo';
* mondeo.year = 2010;
* mondeo.miles = 5000;
* mondeo.toString();
*/
function Car() {};
Car.prototype = {
constructor: Car,
model: '',
year: 0,
miles: 0,
toString: function () {
return this.model + ' has done ' + this.miles + ' miles.';
}
};
/**
* @module
* @description 模式示例:汽车构造器
* @example
* var yourCar = Object.create(myCar);
* console.log(yourCar.name);
*/
var myCar = {
name: 'Ford Mondeo',
drive: function () {
console.log('I am driving.');
},
panic: function () {
console.log('Wait, how do you stop this thing?');
}
};
/**
* @module
* @description 模块模式示例:汽车构造器
* @example
* car.toString();
* car.reconfig({
* model: 'civic',
* year: 2009,
* miles: 20000
* });
*/
var car = {
wheels: 4,
// 配置
config: {
model: 'Ford Mondeo',
year: 2010,
miles: 5000
},
// 基本方法
toString: function () {
return this.model + ' has done ' + this.miles + ' miles.';
},
// 重写当前配置
reconfig: function (newConfig) {
if (typeof newConfig === 'object') {
this.config = newConfig;
return this.config.model;
}
}
};
Car.color = 'blue';
;
/**
* @module
* @description 模块模式示例:购物车
* @example
* cartModule.addItem({item: 'food', price: 5});
* cartModule.addItem({item: 'wine', price: 20});
* cartModule.getItemCount(); // ==> 2
* cartModule.getTotal(); // ==> 25
*/
var cartModule = (function () {
/**
* @description 私有的购物车对象
* @type {Array}
*/
var cart = [];
/**
* @description 私有的方法
*/
function privateMethods () {
console.log('这个私有方法工作了。');
}
/**
* @return {Object} - 暴露公有对象,被自动赋值给 cartModule
*/
return {
/**
* @description 添加物品到购物车
* @param {Object} val - 需要添加的物品
* @property {String} item - 物品名称
* @property {Number} price - 物品单价
*/
addItem: function (val) {
cart.push(val);
},
/**
* @description 获取购物车里的物品数
* @return {Number} - 购物车里的物品数
*/
getItemCount: function () {
return cart.length;
},
/**
* @description 获取购物车里的物品总值
* @return {[type]} [description]
*/
getTotal: function () {
var itemCount = this.getItemCount();
var total = 0;
while (itemCount--) {
total += cart[itemCount].price;
};
return total;
},
/**
* @description 私有方法的公有形式别名
* @type {Function}
*/
aliasPrivateMethods: privateMethods,
};
})();
/**
* @module
* @description 揭示模块示例:简单问候
* @example
* greetingModule.setName('Me');
* greetingModule.getName(); // ==> Name: Me
* greetingModule.greeting; // ==> "Hello, world!"
*/
var greetingModule = function () {
var privateVar = 'FooBar';
var publicVar = 'Hello, world!';
function privateMethod() {
console.log('Name: ' + privateVar);
}
function publicSetName(name) {
privateVar = name;
}
function publicGetName() {
privateMethod();
}
// 将暴露的公有指针指向私有方法及属性上;
return {
setName: publicSetName,
getName: publicGetName,
greeting: publicVar,
};
}();
/**
* @module
* @description 单例模式示例:创建随机数字
* @example
* var randomNumberA = randomNumberModule.getInstance();
* var randomNumberB = randomNumberModule.getInstance();
* randomNumberA.getRandomNum() === randomNumberB.getRandomNum(); // ==> true
*/
var randomNumberModule = (function () {
var instance;
function init() {
// 私有变量;
var privateVar = '私有变量';
var privateRandomNum = Math.random();
// 私有方法;
function privateMethod() {
console.log('私有方法工作了。');
}
// 返回公有变量及公有方法;
return {
publicProp: '公有变量',
publicMethod: function () {
console.log('公有方法工作了。');
},
getRandomNum: function () {
return privateRandomNum;
},
};
}
return {
/**
* @description 获取单例模块的实例
* 1. 如若存在则返回;
* 2. 如若不存在则创建;
*/
getInstance: function () {
if (!instance) {
instance = init();
}
return instance;
}
};
})();
/**
* @module
* @description 观察者模式示例:自定义事件
*/
function EventTarget(){
this.handlers = {};
}
EventTarget.prototype = {
constructor: EventTarget,
addHandler: function(type, handler){
// 如果 EventTarget 的实例上还没有该事件类型,便建立该事件类型
if (typeof this.handlers[type] === 'undefined'){
this.handlers[type] = [];
}
// 如果已有该事件类型,便将事件处理程序推入该事件的处理程序列表中
this.handlers[type].push(handler);
},
fire: function(event){
if (!event.target){
event.target = this;
}
// 检查事件类型是否已注册
if (this.handlers[event.type] instanceof Array){
// handlers 为所有事件处理程序的数组
var handlers = this.handlers[event.type];
// 触发数组中的每一个事件处理程序
for (var i = 0, len = handlers.length; i < len; i++){
handlers[i](event);
}
}
},
removeHandler: function(type, handler){
// 检查事件类型是否已注册
if (this.handlers[type] instanceof Array){
var handlers = this.handlers[type];
// 遍历寻找事件处理程序
for (var i = 0, len = handlers.length; i < len; i++){
if (handlers[i] === handler){
break;
}
}
// 删除传入的事件处理程序的对应项
handlers.splice(i, 1);
}
}
};
/**
* @example
* @description 处理方法
* @param {Object} event - 待处理的事件对象
*/
function handleMessage(event) {
console.log('Message received: ' + event.message);
}
// 创建一个新对象
var target = new EventTarget();
// 添加一个事件处理程序
target.addHandler('message', handleMessage);
// 触发事件,以事件对象的形式传入事件的相关信息
target.fire({
type: 'message',
message: 'Hello world!'
});
// ==> Message received: Hello world!
// 删除事件处理程序
target.removeHandler('message', handleMessage);
// 删除后无法再触发
target.fire({
type: 'message',
message: 'Foo Bar!'
});
示例——
<!DOCTYPE html>
<html>
<head>
<title>Observer Demo</title>
</head>
<body>
<button id="addNewObserver">Add New Observer checkbox</button>
<input id="mainCheckbox" type="checkbox" />
<div id="observerContainer"></div>
<script type="text/javascript">
/**
* @description 模拟一个目标可能拥有的一系列依赖 Observer
*/
function ObserverList() {
this.observerList = [];
}
ObserverList.prototype.Add = function(obj) {
return this.observerList.push(obj);
};
ObserverList.prototype.Empty = function() {
this.observerList = [];
};
ObserverList.prototype.Count = function() {
return this.observerList.length;
};
ObserverList.prototype.Get = function(index) {
if (index > -1 && index < this.observerList.length) {
return this.observerList[index];
}
};
ObserverList.prototype.Insert = function(obj, index) {
var pointer = 1;
if (index === 0) {
this.observerList.unshift(obj);
pointer = index;
} else if (index === this.observerList.length) {
this.observerList.push(obj);
pointer = index;
};
return pointer;
};
ObserverList.prototype.IndexOf = function(obj, startIndex) {
var i = startIndex;
var pointer = -1;
var len = this.observerList.length;
while (i < len) {
if (this.observerList[i] === obj) {
pointer = i;
};
i++;
};
return pointer;
};
ObserverList.prototype.RemoveIndexAt = function(index) {
if (index === 0) {
this.observerList.shift();
} else if (index === this.observerList.length - 1) {
this.observerList.pop();
};
};
function extend(obj, extension) {
for (var key in obj) {
extension[key] = obj[key];
}
}
/**
* @description 模拟目标及其在观察者列表上添加、删除或通知观察者的能力
*/
function Subject() {
this.observers = new ObserverList();
}
Subject.prototype.AddObserver = function(observer) {
this.observers.Add(observer);
};
Subject.prototype.RemoveObserver = function(observer) {
this.observers.RemoveIndexAt(this.observers.IndexOf(observer, 0));
};
Subject.prototype.Notify = function(context) {
var observerCount = this.observers.Count();
for (var i = 0; i < observerCount; i++) {
this.observers.Get(i).Update(context);
}
};
/**
* @description 创建新的 Observer
*/
function Observer() {
this.Update = function (value) {
this.checked = value;
};
};
</script>
<script type="text/javascript">
var button = document.getElementById('addNewObserver');
var input = document.getElementById('mainCheckbox');
var div = document.getElementById('observerContainer');
/**
* 具体目标
*/
// 用 Subject 扩展 input;
extend(new Subject(), input);
// 单击 input 触发通知到观察者上
input.onclick = new Function('input.Notify(input.checked)');
button.onclick = AddNewObserver;
/**
* 具体观察者
*/
function AddNewObserver() {
// 创建需要添加的新 checkbox
var check = document.createElement('input');
check.type = 'checkbox';
// 利用 Observer 类扩展 checkbox
extend(new Observer(), check);
// 重写自定义行为
// check.Update = function (value) {
// this.checked = value;
// };
// 为主 subject 的观察者列表添加新的观察者
input.AddObserver(check);
// 将观察者附加到容器上
div.appendChild(check);
}
</script>
</body>
</html>
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8" />
<title>PubSub Demo</title>
</head>
<body>
<script type="text/javascript">
/**
* @module
* @description 发布订阅模式模块示例:收发邮件系统
*/
var pubsub = {};
(function (q) {
// 主题及订阅者对象
var topics = {};
var subUid = -1;
/**
* @description 发布事件
* @param {String} topic - 指定主题
* @param {*} args - 附带参数
* @return {Object} - 返回 pubsub 对象
*/
q.publish = function (topic, args) {
// 指定主题不存在则返回
if (!topics[topic]) {
return false;
}
// 获取指定主题下的订阅者及其个数
var subscribers = topics[topic];
var len = subscribers ? subscribers.length : 0;
// 逐个执行该主题上订阅者的回调方法
while (len--) {
subscribers[len].func(topic, args);
}
return this;
};
/**
* @description 订阅事件,topic/event 触发时执行事件
* @param {String} topic - 指定主题
* @param {Function} func - 回调方法
* @return {String} token - 标记
*/
q.subscribe = function (topic, func) {
// 指定主题不存在则创建
if (!topics[topic]) {
topics[topic] = [];
}
var token = (++subUid).toString();
// 指定主题中新增订阅者
topics[topic].push({
token: token,
func: func
});
return token;
};
/**
* @description 取消订阅
* @param {String} token - 订阅者的标记
* @return {String} token - 更新的标记
*/
q.unsubscribe = function (token) {
for (var m in topics ) {
if (topics[m]) {
for (var i = 0, len = topics[m].length; i < len; i++) {
// 依据 token 删除订阅者
if (topics[m][i].token === token) {
topics[m].splice(i, 1);
return token;
}
}
}
}
return this;
}
}(pubsub));
</script>
<script type="text/javascript">
/**
* @description 消息记录器
* @param {Object} topics - 通过订阅者接收到主题
* @param {*} data - 数据
*/
var messageLoader = function (topics, data) {
console.log('Logging: ' + topics + ': ' + data);
};
// 订阅者监听订阅的主题,一旦该主题广播一个通知,订阅者就调用回调函数
var subscription = pubsub.subscribe('inbox/newMessage', messageLoader);
// 发布者发布程序感兴趣的主题或通知
pubsub.publish('inbox/newMessage', 'Hello world');
// ==> Logging: inbox/newMessage: Hello world
// 取消订阅
pubsub.unsubscribe(subscription);
pubsub.publish('inbox/newMessage','Foo Bar.');
</script>
</body>
</html>
var mediator = (function () {
var topics = {};
var subscribe = function () {
if (!topics[topic]) {
topics[topic] = [];
}
topics[topic].push({
context: this,
callback: fn
});
return this;
};
var publish = function () {
var args;
if (!topics[topic]) {
return false;
}
args = Array.prototype.slice.call(arguments, 1);
for (var i = 0, l = topics[topic].length; i < l; i++) {
var subscription = topics[topic][i];
subscription.callback.apply(subscription.context, args);
}
return this;
};
return {
Publish: publish,
Subscribe: subscribe,
installTo: function (obj) {
obj.subscribe = subscribe;
obj.publish = publish;
}
};
})
(function () {
var CarManager = {
// 请求信息
requestInfo: function (model, id) {
return 'The information for ' + model + ' with ID ' + id + ' is foobar';
},
// 订购汽车
buyVehicle: function (model, id) {
return 'You have successfully purchased Item ' + id + ', a ' + model;
},
// 组织一个view
arrangeViewing: function (model, id) {
return 'You have successfully booked a viewing of ' + model+'('+id +')';
}
};
})();
var addMyEvent = function (el, ev, fn) {
if (el.addEventListener) {
el.addEventListener(ev, fn, false);
} else if (el.attachEvent) {
el.attachEvent('on' + ev, fn);
} else {
el['on' + ev] = fn;
}
};
/**
* @module
* @description 工厂模式示例:汽车构造器
* @example
* var mondeo = new Car('Ford Mondeo', 2010, 5000);
* mondeo.toString();
*/
var Car = (function () {
var action = ' has done ';
var unit = ' miles.';
var Car = function (model, year, miles) {
this.model = model;
this.year = year;
this.miles = miles;
this.toString = function (){
return this.model + action + this.miles + unit;
};
};
return function (model, year, miles) {
return new Car(model, year, miles);
};
})();
var page = page || {};
page.dom = page.dom || {};
// 子函数 1:处理文本
page.dom.Text = function () {
this.insert = function (where) {
var txt = document.createTextNode(this.url);
where.appendChild(txt);
};
};
// 子函数 2:处理链接
page.dom.Link = function () {
this.insert = function (where) {
var link = document.createElement('a');
link.href = this.url;
link.appendChild(document.createTextNode(this.url));
where.appendChild(link);
};
};
// 子函数 3:处理图片
page.dom.Image = function () {
this.insert = function (where) {
var im = document.createElement('img');
im.src = this.url;
where.appendChild(im);
};
};
// 定义工厂处理函数
/**
* @module
* @description 工厂处理函数
* @example
* var o = page.dom.factory('Link');
* o.url = 'http://www.cnblogs.com';
* o.insert(document.body);
*/
page.dom.factory = function (type) {
return new page.dom[type];
}
// 定义简单的 Car 构造函数
var Car = function (settings) {
this.model = settings.model || 'no model provided';
this.color = settings.color || 'no colour provided';
};
// Mixin
var Mixin = function () {};
Mixin.prototype = {
driveForward: function () {
console.log('drive forward');
},
driveBackward: function () {
console.log('drive backward');
},
driveSideways: function () {
console.log('drive sideways');
}
};
// 通过一个方法将现有对象扩展到另外一个对象上
function augment(receivingClass, givingClass) {
// 只提供特定的方法
if (arguments[2]) {
for (var i = 2, len = arguments.length; i < len; i++) {
receivingClass.prototype[arguments[i]] = givingClass.prototype[arguments[i]];
}
}
// 提供所有方法
else {
for (var methodName in givingClass.prototype) {
// 确保接收类不包含所处理方法的同名方法
if (!Object.hasOwnProperty(receivingClass.prototype, methodName)) {
receivingClass.prototype[methodName] = givingClass.prototype[methodName];
}
// 另一方式:
// if ( !receivingClass.prototype[methodName] ) {
// receivingClass.prototype[methodName] = givingClass.prototype[methodName];
// }
}
}
}
// 给 Car 构造函数增加 driveForward 和 driveBackward 两个方法
augment(Car, Mixin, 'driveForward', 'driveBackward');
// 创建一个新 Car
var myCar = new Car({
model: 'Ford Escort',
color: 'blue'
});
// 测试确保新增方法可用
myCar.driveForward(); // ==> drive forward
myCar.driveBackward(); // ==> drive backward
// 也可以通过不声明特定方法名的形式,将 Mixin 的所有方法都添加到 Car 里
augment(Car, Mixin);
var mySportsCar = new Car({
model: 'Porsche',
color: 'red'
});
mySportsCar.driveSideways(); // ==> drive sideways
var tree = {};
tree.decorate = function () {
console.log('Make sure the tree won\'t fall');
};
tree.getDecorator = function (deco) {
tree[deco].prototype = this;
return new tree[deco];
};
tree.RedBalls = function () {
this.decorate = function () {
// 第 7 步:先执行原型(这时候是 Angel 了)的 decorate 方法
this.RedBalls.prototype.decorate();
// 第 8 步:再输出 red
console.log('Put on some red balls');
}
};
tree.BlueBalls = function () {
this.decorate = function () {
// 第 1 步:先执行原型的 decorate 方法
this.BlueBalls.prototype.decorate();
// 第 2 步:再输出 blue
console.log('Add blue balls');
}
};
tree.Angel = function () {
this.decorate = function () {
// 第 4 步:先执行原型(这时候是 BlueBalls 了)的 decorate 方法
this.Angel.prototype.decorate();
// 第 5 步:再输出 angel
console.log('An angel on the top');
}
};
// 第 3 步:将 BlueBalls 对象赋给 tree,这时候父原型里的 getDecorator 依然可用
tree = tree.getDecorator('BlueBalls');
// 第 6 步:将 Angel 对象赋给 tree,这时候父原型的父原型里的 getDecorator 依然可用
tree = tree.getDecorator('Angel');
// 第 9 步:将 RedBalls 对象赋给 tree
tree = tree.getDecorator('RedBalls');
// 第 10 步:执行 RedBalls 对象的 decorate 方法
tree.decorate();
var Book = function(title, author, genre, pageCount, publisherID, ISBN){
this.title = title;
this.author = author;
this.genre = genre;
this.pageCount = pageCount;
this.publisherID = publisherID;
this.ISBN = ISBN;
};
/**
* @description 书籍模块:工厂单例模式
*/
var BookFactory = (function(){
var existingBooks = {};
return {
createBook: function(title, author, genre, pageCount, publisherID, ISBN) {
// 查找之前是否创建
var existingBook = existingBooks[ISBN];
if (existingBook) {
return existingBook;
} else {
// 如果没有,就创建一个,然后保存
var book = new Book(title, author, genre, pageCount, publisherID, ISBN);
existingBooks[ISBN] = book;
return book;
}
}
}
});
/**
* @description 借书管理模块:单例模式
*/
var BookRecordManager = (function(){
var bookRecordDatabase = {};
return {
// 添加借书记录
addBookRecord: function(id, title, author, genre, pageCount, publisherID, ISBN, checkoutDate, checkoutMember, dueReturnDate, availability) {
var book = bookFactory.createBook(title, author, genre, pageCount, publisherID, ISBN);
bookRecordDatabase[id] = {
checkoutMember: checkoutMember,
checkoutDate: checkoutDate,
dueReturnDate: dueReturnDate,
availability: availability,
book: book
};
},
updateCheckoutStatus: function(bookID, newStatus, checkoutDate, checkoutMember, newReturnDate) {
var record = bookRecordDatabase[bookID];
record.availability = newStatus;
record.checkoutDate = checkoutDate;
record.checkoutMember = checkoutMember;
record.dueReturnDate = newReturnDate;
},
extendCheckoutPeriod: function(bookID, newReturnDate){
bookRecordDatabase[bookID].dueReturnDate = newReturnDate;
},
isPastDue: function(bookID) {
var currentDate = new Date();
return currentDate.getTime() > Date.parse(bookRecordDatabase[bookID].dueReturnDate);
}
};
});