当同一个方法应用于多个类时,你会得到多态性。例如,字符串和列表都可能具有“反向”方法。两种方法具有相同的名称(“Reverse”)。两种方法都做了非常相似的事情(反转所有字符或反转列表中元素的顺序)。但是每个“反向”方法的实现都是不同的,并且特定于其类。 (换句话说,String 像字符串一样反转自身,而 List 像列表一样反转自身。)
打个比方,您可以对法国厨师或日本厨师说“做晚餐”。每个人都会以自己独特的方式表演“做晚餐”。
实际结果是您可以创建一个“逆向引擎”,它接受一个对象并在其上调用“逆向”。只要对象具有 Reverse 方法,您的 Reversing Engine 就可以工作。
为了扩展厨师的类比,您可以构建一个“Waiterbot”来告诉厨师“做晚餐”。 Waiterbot 不必知道要制作什么类型的晚餐。它甚至不必确保它正在与厨师交谈。重要的是“厨师”(或消防员、自动售货机或宠物食品分配器)知道在被告知“做晚餐”时该做什么。
作为程序员,这为您带来的是更少的代码行以及类型安全或后期绑定。例如,这是一个类型安全和早期绑定的示例(使用我正在编写的类似 c 的语言):
class BankAccount {
void SubtractMonthlyFee
}
class CheckingAccount : BankAccount {}
class SavingsAccount : BankAccount {}
AssessFee(BankAccount acct) {
// This will work for any class derived from
// BankAccount; even classes that don't exist yet
acct.SubtractMonthlyFee
}
main() {
CheckingAccount chkAcct;
SavingsAccount saveAcct;
// both lines will compile, because both accounts
// derive from "BankAccount". If you try to pass in
// an object that doesn't, it won't compile, EVEN
// if the object has a "SubtractMonthlyFee" method.
AssessFee(chkAcct);
AssessFee(saveAcct);
}
这是一个没有类型安全但具有后期绑定的示例:
class DatabaseConnection {
void ReleaseResources
}
class FileHandle {
void ReleaseResources
}
FreeMemory(Object obj) {
// This will work for any class that has a
// "ReleaseResources" method (assuming all
// classes are ultimately derived from Object.
obj.ReleaseResources
}
main() {
DatabaseConnection dbConn;
FileHandle fh;
// You can pass in anything at all and it will
// compile just fine. But if you pass in an
// object that doesn't have a "ReleaseResources"
// method you'll get a run-time error.
FreeMemory(dbConn);
FreeMemory(fh);
FreeMemory(acct); //FAIL! (but not until run-time)
}
举个很好的例子,看看 .NET ToString() 方法。所有类都有它,因为所有类都派生自 Object 类。但是每个类都可以以对自己有意义的方式实现 ToString()。
编辑:简单!=简短,恕我直言