简单工厂模式
本文是记录读JavaScript设计模式之简单工厂模式的笔记
简单工厂模式:通常是使用一个函数,通过传递的参数来生成指定的类的实例来达到批量生成相似的对象
function createShape(name){
var res = {};
switch(name){
case "rectangle":
res = new Rectangle();
break;
case "circle":
res = new Circle();
break;
case "square":
res = new Square();
break;
}
return res;
}
function Rectangle(){
this.width = 10;
this.height = 20;
}
Rectangle.prototype.perimeter = function(){
return (this.width + this.height) * 2;
}
Rectangle.prototype.setWidth = function(width){
this.width = width;
}
Rectangle.prototype.setHeight = function(height){
this.height = height;
}
function Square(){
this.width = 10;
}
Square.prototype.perimeter = function(){
return this.width * 4;
}
Square.prototype.setWidth = function(width){
this.width = width;
}
function Circle(){
this.r = 10;
}
Circle.prototype.perimeter = function(){
return 2 * Math.PI * this.r;
}
Circle.prototype.setR = function(r){
this.r = r;
}
var r = createShape("rectangle");
var c = createShape("circle");
var s = createShape("square");
console.log(r.perimeter(), c.perimeter(), s.perimeter())