读JavaScript设计模式之简单工厂模式有感

简单工厂模式

本文是记录读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())
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值