工厂模式(creational 1)

281 阅读1分钟

1.创建型模式(creational 5)

1.1 工厂模式(factory)

  • 定义一个创建对象的接口,让子类决定具体实例化哪一个对象。
function bmwFactory(type) {
  if (type === 'X5')
    return new Bmw(type, 108000, 300);
  if (type === 'X6')
    return new Bmw(type, 111000, 320);
}

function Bmw(model, price, maxSpeed) {
  this.model = model;
  this.price = price;
  this.maxSpeed = maxSpeed;
}

module.exports = bmwFactory;

测试用例

const expect = require('chai').expect;
const bmwFactory = require('../src/creational/factory/factory');

describe('factory test', () => {
  it('sanity', () => {
    var x5 = bmwFactory('X5');
    var x6 = bmwFactory('X6');

    expect(x5.price).to.equal(108000);
    expect(x6.price).to.equal(111000);
    expect(x5.maxSpeed).to.equal(300);
    expect(x6.maxSpeed).to.equal(320);
  });
});

es6 写法

class BmwFactory {

  static create(type) {
    if (type === 'X5')
      return new Bmw(type, 108000, 300);
    if (type === 'X6')
      return new Bmw(type, 111000, 320);
  }
}

class Bmw {
  constructor(model, price, maxSpeed) {
    this.model = model;
    this.price = price;
    this.maxSpeed = maxSpeed;
  }
}

export default BmwFactory;

测试用例

const expect = require('chai').expect;
import BmwFactory from '../src/creational/factory/factory_es6';

describe('Factory es6 test', () => {
  it('We can create a X5 instance', () => {
    const x5 = BmwFactory.create('X5');
    expect(x5.model).to.equal('X5');
  });

  it('The X5 price is properly set', () => {
    const x5 = BmwFactory.create('X5');
    expect(x5.price).to.equal(108000);
  });
});