不暴露创建对象的具体逻辑, 由子类决定实例化哪一类的接口(函数)
用途: 代替new实例化对象
// 产品类
class Product {
deliver () {
console.log('运输')
}
}
class Truck extends Product {
deliver () {
console.log('陆运')
}
}
class Ship extends Product {
deliver () {
console.log('海运')
}
}
// 工厂类
class Factory {
}
class CreateTruck extends Factory {
create () {
return new Truck();
}
}
class CreateShip extends Factory {
create () {
return new Ship();
}
}
let t = new CreateTruck();
t.create().deliver();
let s = new CreateShip();
s.create().deliver();
// 陆运
// 海运