如何在打字稿中模拟多态?

时间:2019-01-08 18:51:15

标签: javascript inheritance polymorphism

我正在尝试在打字稿中模拟OOP概念。我来自Java背景。我面临的问题是,我正在尝试创建一个棋盘游戏。我有像旅馆,监狱,宝藏等的细胞类型。它们都有共同的属性,称为类型数量数量。因此,我创建了一个名为CellType的接口,并将其实现为上述各个类(酒店,宝藏等) 有一个名为Board的类,我想在其中初始化并声明一组预定义的单元格类型。像这样:

  

var cell [:CellType]; //宣言   
酒店=新酒店(200);
      单元格= [Hotel1,Treasure1,Jail1,Hotel2 ..] //初始化

在Java中,我们可以做到:

interface CellType{ public integer amount};
class Hotel implements CellType;
class Jail implements Celltype;
// in main class
ArrayList<CellType> cellTypes = new ArrayList<CellType>;
Hotel Taj = new Hotel();
cellTypes.add(Taj);
Jail jail = new Jail();
cellTypes.add(jail);

那么,我该如何声明多个子类的数组,这些子类继承我们在Java中的继承方式来继承同一超类?

1 个答案:

答案 0 :(得分:1)

接口/类:

  <Hosts>
    <Host Name="Workbook" />
  </Hosts>
  <Requirements>
    <Sets DefaultMinVersion="1.2">
        <Set Name="ExcelApi" MinVersion="1.2"/>
    </Sets>
  </Requirements>
  <DefaultSettings>
    <SourceLocation DefaultValue="" />
  </DefaultSettings>

用法:

interface CellType { amount: number };

class Hotel implements CellType { 
  // This concise syntax creates the public property
  // and assigns to it the value passed into the
  // constructor
  constructor(public amount: number) { }
}

class Jail implements CellType {
  constructor(public amount: number) { }
}

您可以像这样更加简洁:

let cellTypes: Array<CellType> = []; // Or let cellTypes: CellType[] = [];

let taj = new Hotel(100);
cellTypes.push(taj);
let jail = new Jail(200);
cellTypes.push(jail);