简单工厂模式,又叫做静态工厂方法模式。
简单工厂模式的实质,就是由一个工厂类根据传入的参数,动态决定应该创建哪一个产品类的实例。
简单工厂模式主要有三个角色:
1、工厂角色
它是工厂模式的核心,负责实现创建对象的内部逻辑,并根据调用静态方法时传递的参数,决定最终应该创建哪一个对象。
2、对象类角色
它是工厂模式中被工厂方法创建的对象类。
3、具体对象角色
它是工厂模式最终创建出来的对象,所有创建出来的对象都是某一个对象类的实例。
这些概念比较拗口,下面通过一个例子来说明。
<script>
// 声明父类
function Human(){
this.speak = function(str){
console.log(str);
}
this.walk = function(){
console.log("迈动双脚开始走动");
}
}
// 父类获取子类对象的静态方法
Human.gethumaninstance = function(job){
if(job == "student"){
return new Student();
}else if(job == "civil"){
return new Civil();
}else if(job == "Seoer"){
return new Seoer();
}else{
throw "参数为空或非法";
}
}
// 学生子类
function Student(){
this.Work = function(){
console.log("我的主要工作是上课");
}
}
// 公务员子类
function Civil(){
this.Work = function(){
console.log("我的主要工作是喝茶和看报纸");
}
}
// SEOer子类
function Seoer(){
this.Work = function(){
console.log("我的主要工作是创造有价值的东西");
}
}
Student.prototype = new Human();
Civil.prototype = new Human();
Seoer.prototype = new Human();
var xiaoming = Human.gethumaninstance("student");
var lilei = Human.gethumaninstance("civil");
var shidan = Human.gethumaninstance("Seoer");
xiaoming.speak("大家好,我是小明");
lilei.speak("大家好,我是李雷");
shidan.speak("大家好,我是史丹");
xiaoming.walk();
xiaoming.Work();
lilei.Work();
shidan.Work();
</script>
这个例子里,一共有四个类:
Human
Student
Civil
Seoer
后面的三个类都继承于 Human 类。
Human 类中包含一个静态方法:
Human.gethumaninstance()
这个方法接受一个参数,然后根据参数的不同,创建相应的对象。
例如:
var xiaoming = Human.gethumaninstance("student");实际上最终创建的是 newStudent() 而 var lilei=Human.gethumaninstance("civil") 创建的是 newCivil()
简单工厂模式中的三个角色
在这个例子中:
Human 是工厂角色。
它负责根据传入的参数,决定最终应该创建哪一种对象。
Student、Civil 和 Seoer 属于对象类角色。
它们分别代表不同的对象类型。
而:
xiaoming
lilei
shidan
则属于具体的对象角色。
这三个对象并不是直接通过:
newStudent();
newCivil();
newSeoer();
来获取的,而是通过:
Human.gethumaninstance()
这个方法来产生。
也就是说,中间多了一个工厂环节。
这样做的一个好处,就是我们可以把对象的创建过程集中到这个环节中,在这里根据实际情况进行相应的处理。
例如:
Human.gethumaninstance("student");传入的是 student,工厂就返回 Student 对象。
传入的是 civil,就返回 Civil 对象。
传入的是 Seoer,就返回 Seoer 对象。
这样,调用对象的一方就不需要关心具体使用的是哪一个构造函数。
另外,上面的 Student、Civil 和 Seoer 还都继承自 Human:
Student.prototype =newHuman();
Civil.prototype =newHuman();
Seoer.prototype =newHuman();
这样就可以方便地继承 Human 中的公共属性和方法。
所以,这个例子实际上把:
工厂模式和 JavaScript 的对象继承结合到了一起。
简单工厂模式本身的核心并不复杂,最重要的是理解:
调用者负责提出需求,工厂负责根据需求创建具体对象。
评论0
欢迎分享你的看法,也欢迎补充不同的实践经验。