简单工厂模式
本文是记录读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())
本文介绍了一种使用简单工厂模式批量创建相似对象的方法。通过一个JavaScript示例,展示了如何定义不同的形状类并利用工厂函数根据传入的名字参数创建矩形、圆形或正方形对象。


被折叠的 条评论
为什么被折叠?



