- 设计模式总结
- 1、创建型:单例,原型,构造器,工厂,抽象工厂
- 2、结构型:桥接,外观,组合,装饰器,适配器,代理,享元
- 3、行为型:迭代器,解诗琪,观察者,中介者,访问者,状态,备忘录,策略,模板方法,职责链
class AbstructFatory{
createCar(){
throw new Error('不能调用抽象方法,请自己实现');
}
createEngine(){
throw new Error('不能调用抽象方法,请自己实现');
}
}
//实现具体奔驰工厂
class BizFatory extends AbstructFatory{
createCar(){
return new BizCar();
}
createEngine(){
return new BizEngine();
}
}
//实现具体宝马工厂
class BwmFatory extends AbstructFatory{
createCar(){
return new BwmCar();
}
createEngine(){
return new BizEngine();
}
}
//实现抽象产品
class Car{
drive(){
throw new Error('不能调用抽象方法,请自己实现');
}
}
class Engine{
start(){
throw new Error('不能调用抽象方法,请自己实现');
}
}
//实现具体产品
class BizCar extends Car{
drive(){
console.log("BizCar生产出来了")
}
}
class BwmCar extends Car{
drive(){
console.log("BwmCar生产出来了")
}
}
class BizEngine extends Engine{
start(){
console.log("BizEngine生产出来了")
}
}
class BwmEngine extends Engine{
start(){
console.log("BwmEngine生产出来了")
}
}
//实例化
const bizCar = new BizFatory().createCar();
const bizEngine = new BizFatory().createEngine();
const bwmCar = new BwmFatory().createCar();
const bwmEngine = new BwmFatory().createEngine();
bizCar.drive();
bizEngine.start();
bwmCar.drive();
bwmEngine.start();
//新需求,增加一个布加迪威龙车与引擎(符合开闭原则)
class BugattiVeyronCar extends Car{
drive(){
console.log("布加迪威龙生产出来了")
}
}
class BugattiVeyronEngine extends Engine{
start(){
console.log("布加迪威龙引擎生产出来了")
}
}
class BugattiVeyronFatory extends AbstructFatory{
createCar(){
return new BugattiVeyronCar();
}
createEngine(){
return new BugattiVeyronEngine();
}
}
const bugattiVeyronCar = new BugattiVeyronFatory().createCar();
const bugattiVeyronEngine = new BugattiVeyronFatory().createEngine();
bugattiVeyronCar.drive();
bugattiVeyronEngine.start();