工厂模式:使用者不需要关注怎么创建的示例,只需要根据具体需要去工厂获得对象即可。
<!DOCTYPE html>
<html>
<head>
<meta chart="utf-8" />
<title>工厂模式</title>
</head>
<body>
<script>
var Cat = function(){
this.name="i'm a Cat"
}
Cat.prototype.getName = function(){
console.log(this.name)
}
var Bird = function(){
this.name="i'm Bird"
}
Bird.prototype.getName = function(){
console.log(this.name)
}
var AnimalFactory = function(obj){
switch (obj){
case "cat":
return new Cat();
case "bird":
return new Bird;
}
}
// 通过工厂来创建对象
var cat = new AnimalFactory("cat");
cat.getName();
var bird = new AnimalFactory("bird")
bird.getName();
</script>
</body>
</html>