【问题标题】:Is conditional inheritance possible?有条件继承可能吗?
【发布时间】:2019-06-26 18:10:29
【问题描述】:

我是 OOP 范式的新手,我想知道条件继承是否可以在 TS 中以某种方式实现,这可以消除重复编写代码的需要。以下是我的想法。任何建议都会受到欢迎。

interface Person {
  name: string;
  age: number;
}

interface Animal {
  genre: string;
  age: number;
}

abstract class Base {

  private velocity: number = 1;

  run() {
    // if Person extends base return velocity * 0.2; ??
    return this.velocity * 0.4;
  }
}

class Human extends Base implements Person {
  ...
}

class Dog extends Base implements Animal{
  ...
}

let marie = new Human('Marie', 22);
marie.run() //should be 0.2

let bennie = new Dog(...);
bennie.run() // should be 0.4

无论如何它可以工作还是唯一的可能性是在基类中将方法声明为抽象,然后分别为这两种情况实现它?

【问题讨论】:

    标签: typescript oop inheritance


    【解决方案1】:

    通常的方法是保存一个在初始化期间设置的乘数,也许是让子类将它提供给超类:

    abstract class Base {
    
      private velocity: number = 1;
    
      constructor(private multiplier) {           // <===
      }
    
      run() {
        return this.velocity * this.multiplier;
      }
    }
    
    class Human extends Base implements Person {
      constructor() {
        super(0.2);                               // <===
      }
    }
    
    class Dog extends Base implements Animal{
      constructor() {
        super(0.4);                               // <===
      }
    }
    

    有多种方法可以提供乘数,但这只是一个示例。

    【讨论】:

    • 确实在这个例子中它似乎工作。但是我需要将一个类型传递给父抽象方法,并根据传递的类型,返回一些仅适用于该类型的非常具体的属性。即class Person {...} abstract class Base { constructor(private t: Person | Animal) {}; run() { if(this.t instanceof Person) { return ('Run Forest run!!!'); } return ('Run Dog run away!'); } } class Human extends Base implements Person { constructor(...) { super(new Person()) }; } 在我看来,这有点反模式。
    猜你喜欢
    • 2023-03-28
    • 1970-01-01
    • 1970-01-01
    • 2018-03-25
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-01-15
    • 1970-01-01
    相关资源
    最近更新 更多