【问题标题】:Pattern or construct to set default values for multiple classes implementing an interface为实现接口的多个类设置默认值的模式或构造
【发布时间】:2020-03-20 09:20:53
【问题描述】:

我发现自己重复了很多代码,大致如下:

interface IMyInterface {
  commonA: string;
  commonB: string;
}

class Foo implements IMyInterface {
  commonA: string = "hello";
  commonB: string = "world";
  foo: string = "Foo!";
}

class Bar implements IMyInterface {
  commonA: string = "hello";
  commonB: string = "world";
  bar: string = "Bar!";
}

在我的例子中,我有很多类都共享commonAcommonB,但在其他方面有所不同。现在,我知道我不能在界面中设置默认值,但是是否有一些设计模式或 TS 构造可以让我在一个地方定义默认值?

【问题讨论】:

    标签: typescript class design-patterns interface


    【解决方案1】:

    接口不应该具有默认值或任何值,但您绝对可以使用 抽象类 来实现这一点。 https://www.typescriptlang.org/docs/handbook/classes.html#abstract-classes

    interface IMyInterface {
      commonA: string;
      commonB: string;
    }
    
    abstract class Base implements IMyInterface {
      commonA: string = "hello";
      commonB: string = "world";
    }
    
    class Foo extends Base {
      foo: string = "Foo!";
    }
    
    class Bar extends Base {
      bar: string = "Bar!";
    }
    
    

    更多关于抽象类和接口的区别:http://dotnetpattern.com/typescript-abstract-class

    【讨论】:

    • 完美,这正是我想要的。感谢您刷新 OOP 101 ;)
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2017-03-11
    • 2014-10-01
    • 2011-07-12
    • 1970-01-01
    • 1970-01-01
    • 2019-10-26
    • 1970-01-01
    相关资源
    最近更新 更多