什么是多态性,它的用途是什么,如何使用它?
当前回答
从理解和应用PHP多态性,感谢Steve Guidetti。
Polymorphism is a long word for a very simple concept. Polymorphism describes a pattern in object oriented programming in which classes have different functionality while sharing a common interface. The beauty of polymorphism is that the code working with the different classes does not need to know which class it is using since they’re all used the same way. A real world analogy for polymorphism is a button. Everyone knows how to use a button: you simply apply pressure to it. What a button “does,” however, depends on what it is connected to and the context in which it is used — but the result does not affect how it is used. If your boss tells you to press a button, you already have all the information needed to perform the task. In the programming world, polymorphism is used to make applications more modular and extensible. Instead of messy conditional statements describing different courses of action, you create interchangeable objects that you select based on your needs. That is the basic goal of polymorphism.
其他回答
让我们打个比方。对于一个特定的音乐剧本,每个演奏它的音乐家都有自己的诠释。
音乐家可以用接口抽象,音乐家所属的流派可以是一个抽象类,它定义了一些全局解释规则,每个演奏的音乐家都可以用具体类建模。
如果你是音乐作品的听众,你可以参考剧本,例如巴赫的“富加与托卡塔”,每个演奏它的音乐家都以自己的方式多态地演奏。
这只是一个可能的设计示例(在Java中):
public interface Musician {
public void play(Work work);
}
public interface Work {
public String getScript();
}
public class FugaAndToccata implements Work {
public String getScript() {
return Bach.getFugaAndToccataScript();
}
}
public class AnnHalloway implements Musician {
public void play(Work work) {
// plays in her own style, strict, disciplined
String script = work.getScript()
}
}
public class VictorBorga implements Musician {
public void play(Work work) {
// goofing while playing with superb style
String script = work.getScript()
}
}
public class Listener {
public void main(String[] args) {
Musician musician;
if (args!=null && args.length > 0 && args[0].equals("C")) {
musician = new AnnHalloway();
} else {
musician = new TerryGilliam();
}
musician.play(new FugaAndToccata());
}
多态:
这就是面向对象编程的概念。不同对象以自己的方式响应相同消息的能力称为多态性。
多态性源于每个类都存在于自己的名称空间中。在类定义中赋值的名称与在类定义之外赋值的名称不冲突。对象数据结构中的实例变量和对象的方法都是这样:
正如C结构的字段位于受保护的名称空间中一样,因此 对象的实例变量。 方法名也受到保护。与C函数名不同, 方法名不是全局符号。其中一个方法的名称 类不能与其他类中的方法名冲突;两个 非常不同的类可以实现同名的方法。
方法名是对象接口的一部分。当发送请求对象执行某项操作的消息时,该消息命名对象应该执行的方法。因为不同的对象可以具有同名的方法,所以必须相对于接收消息的特定对象来理解消息的含义。发送给两个不同对象的相同消息可以调用两个不同的方法。
多态的主要好处是它简化了编程接口。它允许建立可以在一个又一个类中重用的约定。您不必为添加到程序中的每个新函数都发明一个新名称,而是可以重用相同的名称。编程接口可以被描述为一组抽象行为,与实现它们的类完全不同。
例子:
例1:这是一个用Python 2.x编写的简单示例。
class Animal:
def __init__(self, name): # Constructor of the class
self.name = name
def talk(self): # Abstract method, defined by convention only
raise NotImplementedError("Subclass must implement abstract method")
class Cat(Animal):
def talk(self):
return 'Meow!'
class Dog(Animal):
def talk(self):
return 'Woof! Woof!'
animals = [Cat('Missy'),
Dog('Lassie')]
for animal in animals:
print animal.name + ': ' + animal.talk()
例2:多态性在Java中使用方法重载和方法重写概念实现。
让我们以Car为例来讨论多态性。比如福特、本田、丰田、宝马、奔驰等品牌,都是汽车类型。
但每一个都有自己的高级功能和更先进的技术涉及到他们的移动行为。
现在让我们创建一个基本类型Car
Car.java
public class Car {
int price;
String name;
String color;
public void move(){
System.out.println("Basic Car move");
}
}
让我们实现Ford Car的例子。
Ford扩展Car类型以继承其所有成员(属性和方法)。
Ford.java
public class Ford extends Car{
public void move(){
System.out.println("Moving with V engine");
}
}
上面的Ford类扩展了Car类,也实现了move()方法。尽管Ford已经通过继承可以使用move方法,但Ford仍然以自己的方式实现了该方法。这称为方法重写。
Honda.java
public class Honda extends Car{
public void move(){
System.out.println("Move with i-VTEC engine");
}
}
就像Ford一样,Honda也扩展了Car类型,并以自己的方式实现了move方法。
方法重写是启用多态性的一个重要特性。使用方法重写,子类型可以更改通过继承可用的方法的工作方式。
PolymorphismExample.java
public class PolymorphismExample {
public static void main(String[] args) {
Car car = new Car();
Car f = new Ford();
Car h = new Honda();
car.move();
f.move();
h.move();
}
}
多态性示例输出:
在PolymorphismExample类的主方法中,我创建了三个对象——Car, Ford和Honda。这三个对象都是由Car类型引用的。
请注意一个重要的一点,超类类型可以引用对象的子类类型,但反之则不可能。原因是父类的所有成员都可以通过继承对子类可用,并且在编译期间,编译器会尝试评估我们正在使用的引用类型是否具有他试图访问的方法。
因此,对于多态例子中的引用car,f和h, move方法存在于car类型中。因此,编译器通过编译过程没有任何问题。
但是当涉及到运行时执行时,虚拟机调用对象上的方法,这些方法是子类型。因此,move()方法从它们各自的实现中调用。
因此,所有对象都是Car类型的,但在运行时,执行取决于调用所发生的对象。这就是所谓的多态性。
多态性是一种将对象类视为父类的能力。
例如,假设有一个类叫Animal,还有一个类叫Dog,它继承自Animal。多态性是将任何Dog对象视为Animal对象的能力,如下所示:
Dog* dog = new Dog;
Animal* animal = dog;
什么是多态性?
多态性是一种能力:
调用专门化类型实例上的操作时,只知道其泛化类型,而调用专门化类型的方法,而不调用泛化类型的方法: 这就是动态多态性。 定义几个具有保存名称但参数不同的方法: 这是静态多态。
首先是历史定义,也是最重要的。
多态用于什么?
它允许创建类层次结构的强类型一致性,并做一些神奇的事情,比如管理不同类型的对象列表,而不知道它们的类型,只知道它们的父类型之一,以及数据绑定。
强类型和弱类型
样本
这里有一些形状,如点、线、矩形和圆,它们的Draw()操作要么不接受任何参数,要么使用参数设置超时来删除它们。
public class Shape
{
public virtual void Draw()
{
DoNothing();
}
public virtual void Draw(int timeout)
{
DoNothing();
}
}
public class Point : Shape
{
int X, Y;
public override void Draw()
{
DrawThePoint();
}
}
public class Line : Point
{
int Xend, Yend;
public override Draw()
{
DrawTheLine();
}
}
public class Rectangle : Line
{
public override Draw()
{
DrawTheRectangle();
}
}
var shapes = new List<Shape> { new Point(0,0), new Line(0,0,10,10), new rectangle(50,50,100,100) };
foreach ( var shape in shapes )
shape.Draw();
这里Shape类和Shape. draw()方法应该被标记为抽象。
它们不是用来理解的。
解释
如果没有多态性,使用抽象-虚拟-重写,在解析形状时,只调用Spahe.Draw()方法,因为CLR不知道要调用什么方法。它调用我们所作用的类型的方法,这里的类型是Shape,因为列表声明。所以代码什么都不做。
通过多态性,CLR能够推断我们使用所谓的虚拟表所操作的对象的真实类型。它调用good方法,如果Shape是Point调用Shape。draw ()所以代码画出了形状。
更多的阅读
c# -多态性(1级)
Java中的多态性(要求等级2)
多态性(c#编程指南)
虚方法表
简单类比解释
美国的总统采用多态。怎么做?他有很多顾问:
军事顾问 法律顾问 核物理学家(作为顾问) 等等。
每个人只应该对一件事负责:
总统不是镀锌层专家,也不是量子物理专家。他不知道很多事情。但他知道如何管理国家。
代码也是一样:关注点和职责应该被分离到相关的类/人。这使得维护代码更加容易,特别是当您正在进行更改时。变化是不可避免的。当事情发生变化时,您不希望破坏应用程序的其他部分。总统们应该专注于管理国家,而不是进入专业领域的细节:
为什么一个总统知道所有这些具体的事情是一个坏主意?
如果总统明确地告诉人们要做什么,那就意味着总统需要确切地知道要做什么。如果总统自己需要知道具体的事情,这意味着当你需要做出改变时,你需要在两个地方做出改变,而不仅仅是一个地方。
例如,如果EPA改变了污染法律,那么当这种情况发生时:你必须对EPA类和总统类进行更改。在两个地方而不是一个地方更改代码可能是危险的——因为它更难维护。
有没有更好的方法?
有一个更好的方法:总统不需要知道任何事情的细节——他可以从专门负责这些事情的人那里得到最好的建议。
他可以用多态的方法来治理国家。
使用多态方法的例子:
总统所做的就是让人们给他提建议——这就是他在现实生活中所做的——这就是一个好总统应该做的。他的顾问们都有不同的反应,但他们都知道总统是什么意思:Advise()。成百上千的人涌进他的办公室。他们是谁并不重要。总统所知道的是,当他要求他们“建议”时,他们知道如何相应回应:
public class MisterPresident
{
public void RunTheCountry()
{
// assume the Petraeus and Condi classes etc are instantiated.
petraeus.Advise(); // # Petraeus says send 100,000 troops to Fallujah
condolezza.Advise(); // # she says negotiate trade deal with Iran
healthOfficials.Advise(); // # they say we need to spend $50 billion on ObamaCare
}
}
这种方法允许总统在不了解任何军事、医疗或国际外交的情况下管理国家:细节留给专家。总统需要知道的唯一一件事是:“Advise()”。
你不想要的:
public class MisterPresident
{
public void RunTheCountry()
{
// people walk into the Presidents office and he tells them what to do
// depending on who they are.
// Fallujah Advice - Mr Prez tells his military exactly what to do.
petraeus.IncreaseTroopNumbers();
petraeus.ImproveSecurity();
petraeus.PayContractors();
// Condi diplomacy advice - Prez tells Condi how to negotiate
condi.StallNegotiations();
condi.LowBallFigure();
condi.FireDemocraticallyElectedIraqiLeaderBecauseIDontLikeHim();
// Health care
healthOfficial.IncreasePremiums();
healthOfficial.AddPreexistingConditions();
}
}
NO! NO! NO! In the above scenario, the president is doing all the work: he knows about increasing troop numbers and pre-existing conditions. This means that if middle eastern policies change, then the president would have to change his commands, as well as the Petraeus class as well. We should only have to change the Petraeus class, because the President shouldn't have to get bogged down in that sort of detail. He doesn't need to know about the details. All he needs to know is that if he makes one order, everything will be taken care of. All the details should be left to the experts.
这使得总统可以做他最擅长的事情:制定总体政策,保持良好的形象,打高尔夫球。
它实际上是如何实现的——通过基类还是公共接口
简而言之,这实际上就是多态性。具体是怎么做到的呢?通过“实现一个公共接口”或者通过使用基类(继承)——参见上面的回答,它们更详细地说明了这一点。(为了更清楚地理解这个概念,您需要知道接口是什么,还需要了解继承是什么。否则,你可能会很挣扎。)
换句话说,Petraeus、Condi和healthoofficial都是“实现接口”的类——让我们称其为IAdvisor接口,它只包含一个方法:Advise()。但现在我们进入细节。
这是最理想的
public class MisterPresident
{
// You can pass in any advisor: Condi, HealthOfficials,
// Petraeus etc. The president has no idea who it will
// be. But he does know that he can ask them to "advise"
// and that's all Mr Prez cares for.
public void RunTheCountry(IAdvisor governmentOfficer)
{
governmentOfficer.Advise();
}
}
public class USA
{
MisterPresident president;
public USA(MisterPresident president)
{
this.president = president;
}
public void ImplementPolicy()
{
IAdvisor governmentOfficer = getAdvisor(); // Returns an advisor: could be condi, or petraus etc.
president.RunTheCountry(governmentOfficer);
}
}
总结
你真正需要知道的是:
总统不需要知道细节——那些是留给别人的。 总统所需要知道的是问谁曾经走进家门给他建议-我们知道他们绝对知道当被要求建议时该做什么(因为他们实际上都是顾问(或IAdvisors))
我真的希望它能帮到你。如果你不明白任何张贴评论,我会再试一次。