What is polymorphism, what is it for, and how is it used?

前端 未结 28 2777
南笙
南笙 2020-11-21 07:08

What is polymorphism, what is it for, and how is it used?

28条回答
  •  灰色年华
    2020-11-21 07:52

    Simple Explanation by analogy

    The President of the United States employs polymorphism. How? Well, he has many advisers:

    1. Military Advisers
    2. Legal Advisers
    3. Nuclear physicists (as advisers)
    4. Medical advisers
    5. etc etc.

    Everyone Should only be responsible for one thing: Example:

    The president is not an expert in zinc coating, or quantum physics. He doesn't know many things - but he does know only one thing: how to run the country.

    It's kinda the same with code: concerns and responsibilities should be separated to the relevant classes/people. Otherwise you'd have the president knowing literally everything in the world - the entire Wikipedia. Imagine having the entire wikipedia in a class of your code: it would be a nightmare to maintain.

    Why is that a bad idea for a president to know all these specific things?

    If the president were to specifically tell people what to do, that would mean that the president needs to know exactly what to do. If the president needs to know specific things himself, that means that when you need to make a change, then you'll need to make it in two places, not just one.

    For example, if the EPA changes pollution laws then when that happens: you'd have to make a change to the EPA Class and also the President class. Changing code in two places rather than one can be dangerous - because it's much harder to maintain.

    Is there a better approach?

    There is a better approach: the president does not need to know the specifics of anything - he can demand the best advice, from people specifically tasked with doing those things.

    He can use a polymorphic approach to running the country.

    Example - of using a polymorphic approach:

    All the president does is ask people to advise him - and that's what he actually does in real life - and that's what a good president should do. his advisors all respond differently, but they all know what the president means by: Advise(). He's got hundreds of people streaming into his office. It doesn't actually matter who they are. All the president knows is that when he asks them to "Advise" they know how to respond accordingly:

    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
        }
    }
    

    This approach allows the president to run the country literally without knowing anything about military stuff, or health care or international diplomacy: the details are left to the experts. The only thing the president needs to know is this: "Advise()".

    What you DON"T want:

    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.

    This allows the president to do what he does best: set general policy, look good and play golf :P.

    How is it actually implemented - through a base class or a common interface

    That in effect is polymorphism, in a nutshell. How exactly is it done? Through "implementing a common interface" or by using a base class (inheritance) - see the above answers which detail this more clearly. (In order to more clearly understand this concept you need to know what an interface is, and you will need to understand what inheritance is. Without that, you might struggle.)

    In other words, Petraeus, Condi and HealthOfficials would all be classes which "implement an interface" - let's call it the IAdvisor interface which just contains one method: Advise(). But now we are getting into the specifics.

    This would be ideal

        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);
            }
        }
    

    Summary

    All that you really need to know is this:

    • The president doesn't need to know the specifics - those are left to others.
    • All the president needs to know is to ask who ever walks in the door to advice him - and we know that they will absolutely know what to do when asked to advise (because they are all in actuality, advisors (or IAdvisors :) )

    I really hope it helps you. If you don't understand anything post a comment and i'll try again.

提交回复
热议问题