MVC
Module (数据模型)
负责操作所有数据
伪代码示例
class Person{
construcotr(name,age){
this.name;
this.age;
}
getName(){
return this.name
}
setName(name){
eventBus.emit(name);
this.name = name
}
getAge(){
return this.name
}
setAge(age){
this.age = age
}
}
View (视图)
负责所有UI界面
伪代码示例
class PersonView{
printPersonInfo(name,age){
println('person information:')
println('name: '+name)
println('age: '+age)
}
}
Contoller (控制器)
负责其他
伪代码示例
class PersonContoller{
constructor(name,age){
this.view = new PersonView()
this.module = new Person(name,age);
}
setModuleName(name){
this.module.setName(name)
}
setModuleAge(age){
this.module.setName(age)
}
getModuleName(){
this.module.getName()
}
getModuleAge(){
this.module.getAge()
}
renderView(){
this.view.printPersonInfo(this.getModuleName(),this.getModuleAge())
}
}
EventBus
EventBus是使用事件绑定的方式来实现对象的通信,EventBus上有三个方法。
- on 事件绑定
- off 取消事件绑定
- emit 执行事件
实例: 当更新module中的name属性时,触发updata:name事件,触发事件后会执行 controller中 eventBus.on('updata:name',function(){...})绑定的方法。
代码伪代码如下:
class Person{
construcotr(name){
this.name;
}
getName(){
return this.name
}
setName(name){
eventBus.emit("updata:name"); //当数据被更新,触发事件
this.name = name
}
}
class PersonView{
printPersonInfo(name){
println('person information:')
println('name: '+name)
}
}
class PersonContoller{
constructor(name){
this.view = new PersonView()
this.module = new Person(name);
eventBus.on('updata:name',function(){
renderView(); //事件触发执行渲染
})
}
setModuleName(name){
this.module.setName(name)
}
getModuleName(){
this.module.getName()
}
renderView(){
this.view.printPersonInfo(this.getModuleName())
}
}
contollor = PersonContollor("大明")
contollor.renderView(); // print->大明
//设置module中的name属性会触发事件从而执行renderView()
contollor.setModuleName('小红') //print->小红
表驱动
表驱动法就是一种编程模式(scheme)——从表里面查找信息而不使用逻辑语句(if 和case)。事实上,凡是能通过逻辑语句来选择的事物,都可以通过查表来选择。对简单的情况而言,使用逻辑语句更为容易和直白。但随着逻辑链的越来越复杂,查表法也就愈发显得更具吸引力。表驱动不仅能简化逻辑,还能通过抽象出数据结构来简化代码避免代码的重复。
例如输入0~6查看返回今天是星期几
function week(day){
if(day===0){
reutrn "星期天"
}else if(day===1)
return "星期一"
}
...
/**switch**/
switch(day){
case 0:
return "星期天"
break;
...
}
}
将数据抽象出来之后
function week(day){
const weeks = ["星期天","星期一","星期二","星期三","星期四","星期五","星期六"]
return weeks[key];
}
一行代码就搞定。
模块化
模块化可以将一个复杂的功能或不相关的代码分为各个模块来进行处理,这样可以很好的避免代码之间产生的冲突,比如:命名空间、使用的技术类型。使用模块化封装代码可以实现最小知识的原理,开发人员只需要知道引入模块,以及使用改模块的文档,不用关心模块本身是如何实现的,模块中使用了什么依赖。