定义:外观模式又叫门面模式,外观模式为一个系统中的子系统提供一个统一的高层接口,从而方便使用
子系统。
1. 用类实现外观模式
class Cpu {
install() {
console.log('install cpu');
}
}
class Disk {
install() {
console.log('install disk');
}
}
class Memory {
install() {
console.log('install disk');
}
}
class Computer {
constructor() {
this.cpu = new Cpu();
this.disk = new Disk();
this.memory = new Memory();
}
install () {
this.cpu.install();
this.disk.install();
this.memory.install();
}
}
const computer = new Computer();
computer.install();
2. 用函数实现外观模式
const installCpu = () => console.log('install cpu');
const installDisk = () => console.log('install disk');
const installMemory = () => console.log('install memory');
const installComputer = () => {
installCpu();
installMemory();
installDisk();
};
installComputer();
3. 外观模式在js中的应用
- 兼容各浏览器的事件处理差异为用户提供统一调用接口
function addClickEvent(element, fn) {
// most browser support
if(element.addEventListener){
element.addEventListener('click', fn);
console.log('most');
}
// IE8 support
else if (element.attachEvent){
console.log('IE8');
element.attachEvent('onclick', fn);
}
// all the browser support
else {
console.log('all');
element.onclick = fn;
}
}
const el = document.querySelector('#logo');
addClickEvent(el, function(event){
console.log('add click Event');
});
标签:外观,disk,console,log,javascript,element,install,const,设计模式
From: https://www.cnblogs.com/xiaodi-js/p/17203516.html