JavaScript设计模式—工厂模式
工厂模式概念一:就是把参数传进去后,经过一系列的处理,然后得到想要的结果。
工厂模式概念二:就是用面向对象的方法,把一些对象封装, 使一些占用空间多的、重复的代码封装起来的一种模式。
看下面代码:
在开头要先插入CommonUtil.js文件,里面包含检测接口的鸭式辩型法,和继承的方法
CommonUtil.js文件
var BH
={};
BH
.Interface
=function(name
,methods
){
if(arguments
.length
!=2){
throw new Error('this interface interface constructor arguments must be 2 lenght!');
}
this.name
=name
;
this.methods
=[];
for(var i
=0,len
=methods
.length
;i
<len
;i
++){
if(typeof methods
[i
] !== 'string'){
throw new Error('the Interface menthod name is error');
}
this.methods
.push(methods
[i
]);
}
}
BH
.Interface
.ensureImplements
=function(object){
if(arguments
.length
<2){
throw new Error('Interface.ensureImplements methods constructor argumrnts must be > 2 !');
}
for(var i
=1,len
=arguments
.length
;i
<len
;i
++){
var instanceInterface
=arguments
[i
];
if(instanceInterface
.constructor
!== BH
.Interface
){
throw new Error('the arguments construcotr not be Interface Class!');
}
for(var j
=0;j
<instanceInterface
.methods
.length
;j
++){
var methodName
=instanceInterface
.methods
[j
];
if(!object[methodName
] || typeof object[methodName
] !=='function'){
throw new Error('the method name '+ methodName
+' is not found');
}
}
}
}
BH
.extend
=function
(sub
,sup
){
var F
=new Function();
F
.prototype
=sup
.prototype
;
sub
.prototype
=new F();
sub
.prototype
.constructor
=sub
;
sub
.superClass
=sup
.prototype
;
if(sup
.prototype
.constructor
== Object
.prototype
.constructor
){
sup
.prototype
.constructor
=sup
;
}
}
工厂模式
总结:先有一个卖车的店里面有卖车的方法—通过获得用户买车的类型—调用生产车的工厂里面的方法–判断是否能生产这种车能就生产出来–检测该车是否有正常的start run功能–检测没问题再返回给用户(前提是这个生产车的工厂已经规定有哪些车的类型和车的功能)。 这是我看了视频后学到的,理解但还是比较生疏这种模式。大佬们,有什么需要修改或建议的地方欢迎来评论区逛逛哈。