为什么一个对象的类型指的是它的接口? (设计模式:可重用面向对象软件的元素书)

Why does an object's type refer to its interface? (Design Patterns: Elements of Reusable Object-Oriented Software book)

为什么对象的类型指的是它的接口?为什么这里使用术语类型?就C++而言,我无法理解它。

Gamma, Erich. Design Patterns: Elements of Reusable Object-Oriented Software (Addison-Wesley Professional Computing Series) (Kindle Locations 593-596). Pearson Education. Kindle Edition.

An object’s class defines how the object is implemented. The class defines the object’s internal state and the implementation of its operations. In contrast, an object’s type only refers to its interface—the set of requests to which it can respond. An object can have many types, and objects of different classes can have the same type.

Why does object's type refer to its interface? Why the term type is used here? In terms of C++ I am not able to understand it.

OOP 中的对象与现实世界没有太大区别。例如:

  1. A Car IS-A Vehicle。根据这个定义,Car 有能力将 people/cargo 从一个地方运送到另一个地方。
  2. 一个Car也是一个Car。根据这个定义,它具有使用方向盘驱动的能力。

在上面的例子中,aCarIS-ACar和aCar也是aVehicle因为它可以用方向盘驱动cargo/people从一个地方移动到另一个地方。换句话说,现实世界中对象的类型是由您可以用它做的事情定义的(相对于它的界面。)

如果我们在编程中使用上面的类比,CarVehicle 的子类并且具有 Car 对象的代码可以使用 Vehicle 中的所有函数作为以及 Car。这意味着 Car IS-A VehicleCar。总之,对象的类型是由它的接口定义的,即它支持的一组操作。

过于简单化...

  1. 接口 - class 拥有的东西的列表以及它可以做的事情...回答 "Whats" [=11= 的东西的列表]

  2. 实施 - 回答关于 "How" 的问题,"Whats" 已完成。

示例: 一个接口 IPackageMover 做 2 件事和 2 classes(类型)实际实现接口(除了接口要求之外还做其他事情)

 // the interface
 public interface IPackageMover
 {
    string GetName();
    void public void MoveTo(Package package, string newAddress); 
 }

 // the "type" that has the implementation
 public class JoeThePackageMover : IPackageMover
 {
    public string GetName()
    {
        return "Joe";
    }
    public void MoveTo(Package package, string newAddress)
    {
        PickUp(package);
        Drive(newAddress);
        DropOff(package);
    }
    public void PickUp(Package package)
    {
        // do stuff
    }
    public void Drive(string newAddress)
    {
        // do stuff
    }
    public void DropOff(Package package)
    {
        // do stuff
    }
 }

 // another "type" with the same interface
 public class PassTheBuckPackageMover : IPackageMover
 {
    public string GetName()
    {
        return "What do you want it to be?";
    }
    public void MoveTo(Package package, string newAddress)
    {
        var joe = new JoeThePackageMover();
        joe.MoveTo(package, newAddress);            
    }
    public void Chill()
    {
        //do stuff
    }

 }