Appearance
中介者模式
HTML
HTML
<div>
<div>选择颜色、选择内存</div>
<select id="colorSelect">
<option value="">请选择</option>
<option value="red">红色</option>
<option value="blue">蓝色</option>
</select>
<select id="memorySelect">
<option value="">请选择</option>
<option value="32G">32G</option>
<option value="16G">16G</option>
</select>
<div>输入购买数量:</div>
<input
type="text"
id="numberInput"
/>
<br />
您选择了颜色:
<div id="colorInfo"></div>
<br />
您选择了内存:
<div id="memoryInfo"></div>
<br />
您选择了数量:
<div id="numberInfo"></div>
<br />
<button
id="nextBtn"
disabled="true"
>
请选择手机颜色和购买数量
</button>
</div>
JS
JS
// 中介者模式的例子——购买商品
var goods = { // 手机库存
"red|32G": 3,
"red|16G": 0,
"blue|32G": 1,
"blue|16G": 6
};
var mediator = (function () {
var colorSelect = document.getElementById('colorSelect'),
numberInput = document.getElementById('numberInput'),
memorySelect = document.getElementById('memorySelect'),
colorInfo = document.getElementById('colorInfo'),
numberInfo = document.getElementById('numberInfo'),
memoryInfo = document.getElementById('memoryInfo'),
nextBtn = document.getElementById('nextBtn');
return {
changed: function (obj) {
var color = colorSelect.value, // 颜色
memory = memorySelect.value,// 内存
number = numberInput.value, // 数量
stock = goods[color + '|' + memory]; // 颜色和内存对应的手机库存数量
if (obj === colorSelect) { // 如果改变的是选择颜色下拉框
colorInfo.innerHTML = color;
} else if (obj === memorySelect) { // 内存
memoryInfo.innerHTML = memory;
} else if (obj === numberInput) { // 数量
numberInfo.innerHTML = number;
}
if (!color) {
nextBtn.disabled = true;
nextBtn.innerHTML = '请选择手机颜色';
return;
}
if (!memory) {
nextBtn.disabled = true;
nextBtn.innerHTML = '请选择内存';
return;
}
if (((number - 0) | 0) !== (number - 0) || !(number > 0)) {
nextBtn.disabled = true;
nextBtn.innerHTML = '请输入正确的购买数量';
return;
}
if (number > stock) { // 当前选择数量没有超过库存量
nextBtn.disabled = true;
nextBtn.innerHTML = '库存不足';
return;
}
nextBtn.disabled = false;
nextBtn.innerHTML = '放入购物车';
}
}
})()
// 事件函数:
colorSelect.onchange = function () {
mediator.changed(this);
};
memorySelect.onchange = function () {
mediator.changed(this);
};
numberInput.oninput = function () {
mediator.changed(this);
};