Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

interface in OOP & TS #52

Open
spring-fe opened this issue Jan 9, 2019 · 0 comments
Open

interface in OOP & TS #52

spring-fe opened this issue Jan 9, 2019 · 0 comments

Comments

@spring-fe
Copy link
Owner

spring-fe commented Jan 9, 2019

interface in OOP

interface定义一个契约,确保函数实现了接口中的方法。它是对行为的抽象,而具体如何行动需要由类(classes)去实现(implements)。
interface是一个对象行为的描述,例如,当你打开一个灯开关,灯亮了,你不在乎它是怎么亮的,只在乎它亮了。在面向对象中,接口是对对象必须具有的所有的函数的描述。
interface是一个编程语法,强制对象有某些特定的属性。例如,假设我们有一个汽车类、一个滑板车类和一个卡车类。这3个类中每一个都应该有一个start_engine()操作。每辆车的发动机如何启动留给每一个特定的类,但它们必须有一个启动发动机。

public interface Vehicle {
    function start_engine():void;
}

public class Car implements Vehicle {
    function start_engine(): void {
       // code to start the engine of the car...
    }
}

特点

  • 抽象化。汽车、卡车类等都可以实现交通工具接口。
  • 在具体类中对接口的函数有特定的具体实现。汽车有汽车的启动发动机方式,卡车有卡车的启动发动机方式。

interface in TS

在TypeScript除了对行为的抽象,常用于对「对象的形状(Shape)」进行描述。

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

let tom: Person = {
    name: 'Tom',
    age: 25
}

上面的例子中,我们定义了一个接口 Person,接着定义了一个变量 tom,它的类型是 Person。这样,我们就约束了 tom 的形状必须和接口 Person 一致。

[1]https://www.cs.utah.edu/~germain/PPS/Topics/interfaces.html
[2]https://ts.xcatliu.com/basics/type-of-object-interfaces.html

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

1 participant