观察者模式—使用JavaScript实现
2010-09-14 13:23:45 来源:WEB开发网接下来我们将做什么
现在你已经知道了什么是 观察者模式,并且也了解了如何使用JavaScript来创建自己的对象。正如你在图1中看到的一样,你必须在 主题类 中定义2个方法(Attach 和 Detach)。为了达到这个目的,你需要一个 集合 来完成 Attach/Detach 方法。现在是时候写你的第一个JavaScript ArrayList 对象了。在定义 ArrayList 对象之前,你必须知道 ArrayList 能够完成一些什么样的功能。
ArrayList功能列表:
1. Count
2. Add
3. GetAt
4. Clear
5. RemoveAt
6. Insert
7. IndexOf
8. LastIndexOf
function ArrayList()
{
//初始化空数组
this.aList = [];
}
ArrayList.prototype.Count = function()
{
return this.aList.length;
}
ArrayList.prototype.Add = function(object)
{
//把新添加的对象放在数组的最后
return this.aList.push(object);
}
ArrayList.prototype.GetAt = function(index) //index必须是整数
{
if (index > -1 && index < this.aList.length)
{
return this.aList[index];
}
else
{
return undefined; //超出了数组范围,返回undefined
}
}
ArrayList.prototype.clear = function()
{
this.aList = [];
}
ArrayList.prototype.RemoveAt = function(index)
{
var m_count = this.aList.length;
if (m_count > 0 && index > -1 && index < this.aList.length)
{
switch (index)
{
case 0:
//移除数组中的第一个元素
this.aList.shift();
break;
case m_count - 1:
//移除数组中最后一个元素
this.aList.pop();
break;
default:
//获取前面index个元素,生成一个新数组
var head = this.aList.slice(0, index);
//获取index之后的元素,生成一个新数组
var tail = this.aList.slice(index + 1);
//组合两个子数组
this.aList = head.concat(tail);
break;
}
}
}
ArrayList.prototype.Insert = function(object, index)
{
var m_count = this.aList.length;
var m_returnValue = -1;
if (index > -1 && index <= m_count)
{
switch (index)
{
case 0:
this.aList.unshift(object);
m_returnValue = 0;
break;
case m_count:
this.aList.push(object);
m_returnValue = m_count;
break;
default:
var head = this.aList.slice(0, index - 1);
var tail = this.aList.slice(index);
this.aList = header.concat(tail.unshift(object));
m_returnValue = index;
break;
}
}
return m_returnValue;
}
ArrayList.prototype.IndexOf = function(object, startIndex)
{
var m_count = this.aList.length;
var m_returnValue = -1;
if (startIndex > -1 && startIndex < m_count)
{
var i = startIndex;
while (i < m_count)
{
//循环遍历数组,直到找到和参数object相同的元素
if (this.aList[i] == object)
{
m_returnValue = i;
break;
}
i++;
}
}
return m_returnValue;
}
ArrayList.prototype.LastIndexOf = function(object, startIndex)
{
var m_count = this.aList.length;
var m_returnValue = -1;
if (startIndex > -1 && startIndex < m_count)
{
var i = m_count - 1;
while (i >= startIndex)
{
if (this.aList[i] == object)
{
m_returnValue = i;
break;
}
i--;
}
}
return m_returnValue;
}
更多精彩
赞助商链接