Why we do create object instance from Interface instead of Class?

前端 未结 4 1138
春和景丽
春和景丽 2020-12-04 06:53

I have seen an Interface instance being generated from a class many times. Why do we use interface this way? An interface instance is created only itself with the help of th

4条回答
  •  遥遥无期
    2020-12-04 07:30

    Using an interface this way gives you the ability to create methods that use standard template of the interface. So here you might have many classes of printer that all inherit from IPrinter

    class SamsungPrinter : IPrinter
    {
        // Stuff and interface members.
    }
    
    class SonyPrinter : IPrinter
    {
        // Stuff and interface members.
    }
    
    interface IPrinter
    {
        void Print();
    }
    

    So for each type SamsungPrinter, SonyPrinter, etc. you can pre-process using something like

    public static void PreProcessAndPrint(IPrinter printer)
    {
        // Do pre-processing or something.
        printer.Print();
    }
    

    You know from inheriting from IPrinter and using that type in the method parameters that you can always safely use the Print method on what ever object is passed.

    Of course there are many other uses for using interfaces. One example of their use is in design patterns, in particular the Factory and Strategy patterns. The description of which and examples can be found here.

    I hope this helps.

提交回复
热议问题