微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

Javascript:如何在不创建循环依赖关系的情况下重用创建子实例的方法

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 { }

如何在不创建循环依赖关系的情况下进行重组,以便:

>每个类都在单独的文件
> addChild()方法可用于所有子级,而无需重复执行代码

我读过,对于基类来说,了解子类通常是一个糟糕的模式,但是我不确定更好的模式是什么样.

Example that might make more sense

编辑:删除类型作为参数

解决方法:

您需要将抽象类与工厂类分开(创建新实例):

// 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抽象类.这使得List抽象具有3个职责:作为列表,从外部源加载数据和创建新实体.

可维护代码的指导原则是single responsibility principle,其中每个类都有一个职责.

我建议您根据确定的职责将List对象分为3类:抽象类List,类ListFactory和类DataFetcher.

这将使您可以为每个这些类定义一个良好的接口.

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 [email protected] 举报,一经查实,本站将立刻删除。

相关推荐