js设计模式3-抽象工厂模式

本文介绍了一种使用抽象工厂模式创建不同类型实体的实现方法。通过定义一个抽象类,派生出具体工厂类来创建如足球、篮球、自行车和汽车等实体。这种模式允许系统独立于产品的创建、组合和表示。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

这里要多实现一个超级工厂,常见不同的工厂,然后再创建实体,相比工厂模式,继承上要多了一个抽象类的继承

class Football {
  round () {
    console.log('我是脚踢的')
  }
}

class Basketball {
  round () {
    console.log("我是手打的")
  }
}

class Bycle {
  round () {
    console.log("我是用来骑得")
  }
}

class Car {
  round () {
    console.log("我是用来开的")
  }
}
//抽象类
class SuperClass {
  getCar () {
    throw new Error("必须创建改方法")
  }
  getBall () {
    throw new Error("必须创建改方法")
  }
}




//实现工厂
class Mincar extends SuperClass {
  getCar (car) {
    car = car.toLocaleLowerCase();
    switch (car) {
      case 'bycle':
        return new Bycle();
      case 'car':
        return new Car();
      default:
        break;
    }
  }
  getball () {
    return null;
  }
}


class Ball extends SuperClass {
  getball (ball) {
    this.ball = ball.toLocaleLowerCase();
    switch (ball) {
      case 'football':
        return new Football();
      case 'basketball':
        return new Basketball();
      default:
        break;
    }
  }
  getCar () {
    return null;
  }
}



//实现超级类

class Factory {
  constructor(type) {
    this.types = type.toLocaleLowerCase();
    switch (type) {
      case 'ball':
        return new Ball();
      case 'car':
        return new Mincar();
      default:
        break;
    }
  }
}



//实现方式
//创建工厂
const carFac = new Factory('car');
const c1 = carFac.getCar('car');
const c2 = carFac.getCar('Bycle');
c1.round()
c2.round()

我是用来开的
我是用来骑得

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

风清云淡_A

觉得有帮助的话可以给点鼓励

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值