JavaScript es6设计模式 – Factory(工厂模式)

41次阅读
没有评论

Factory(工厂模式)

定义一个用于创建对象的接口,让子类决定将哪一个类实例化。Factory Method使一个类的实例化延迟到其子类。

'use strict';

class Product {
    constructor() {
        console.log('Product Class created');
    }
}

class ConcreteProduct extends Product {
    constructor() {
        super();
        console.log('ConcreteProduct Class created');
    }
}

class Creator {
    constructor() {
        console.log('Creator Class created');
    }

    factoryMethod() {
        console.log('Creator.factoryMethod created');
    }

    anOperation() {
        console.log('Creator.anOperation created');
        this.product = this.factoryMethod();
        console.log(this.product instanceof ConcreteProduct);
    }
}

class ConcreteCreator extends Creator {

    constructor() {
        super();
        console.log('ConcreteCreator Class created');
    }

    factoryMethod() {
        return new ConcreteProduct();
    }
}

var factory = new ConcreteCreator();
factory.anOperation();