代码之家  ›  专栏  ›  技术社区  ›  joshhunt

Javascript:如何重用方法来创建子实例而不创建循环依赖

  •  3
  • joshhunt  · 技术社区  · 6 年前
    abstract class Fruit {
        private content: Fruit[] = [];
    
        addChild() {
            // Pick one at random (using this as an example instead of the actual criteria that determines this)
            const type = pickOne(['apple', 'banana', 'cherry']);
    
            switch (type) {
                case 'apple':
                    this.content.push(new Apple());
                case 'banana':
                    this.content.push(new Banana());
                case 'cherry':
                    this.content.push(new Cherry());
            }
        }
    }
    
    class Apple extends Fruit { }
    
    class Banana extends Fruit { }
    
    class Cherry extends Fruit { }
    

    1. 每个类都在一个单独的文件中
    2. 这个 addChild() 方法可用于所有子级,而无需复制代码

    我已经读到基类了解任何关于子类的知识通常是一种不好的模式,但是我不确定更好的模式应该是什么样子。

    Example that might make more sense

    远离的 type 作为论据

    2 回复  |  直到 6 年前
        1
  •  4
  •   Clément Prévost    6 年前

    您需要从工厂类中拆分抽象类(创建新实例):

    // fruit.ts
    abstract class Fruit {
        private content: Array<Fruit> = [];
    
        addChild(child: Fruit) {
            this.content.push(child);
        }
    }
    
    // fruit-factory.ts
    class FruitFactory {
        create(type: 'apple' | 'banana' | 'cherry'): Fruit {
            switch (type) {
                case 'apple':
                    return new Apple();
                case 'banana':
                    return new Banana();
                case 'cherry':
                    return new Cherry();
            }
        }
    }
    
    // apple.ts
    class Apple extends Fruit { }
    
    // banana.ts
    class Banana extends Fruit { }
    
    // cherry.ts
    class Cherry extends Fruit { }
    

    这个 Factory design pattern 对于隔离和重用创建对象的代码非常有用。

    在更详细的示例中 loadChildren 不必与 List 抽象类。这使得 列表

    可维护代码的指导原则是 single responsibility principle 每个班级都有一个单独的职责。

    我建议你分头行动 列表 abstract class List , class ListFactory class DataFetcher .

    这将允许您为每个类定义一个好的接口。

        2
  •  0
  •   FK82    6 年前

    abstract class Fruit {
        private content: Fruit[] = [];
    
        addChild<F extends Fruit>(C: new (...args: any) => F) {
            this.content.push(new C());
        }
    }
    
    class Apple extends Fruit { }
    
    class Banana extends Fruit { }
    
    class Cherry extends Fruit { }