What are the pros and cons of using interfaces in Delphi?

前端 未结 9 1567
既然无缘
既然无缘 2021-01-31 17:21

I have used Delphi classes for a while now but never really got into using interfaces. I already have read a bit about them but want to learn more.

I would like to hear

相关标签:
9条回答
  • 2021-01-31 18:14

    I mostly use interfaces when I want objects with different ancestry to offer a common service. The best example I can think of from my own experience is an interface called IClipboard:

    IClipboard = interface
      function CopyAvailable: Boolean;
      function PasteAvailable(const Value: string): Boolean;
      function CutAvailable: Boolean;
      function SelectAllAvailable: Boolean;
      procedure Copy;
      procedure Paste(const Value: string);
      procedure Cut;
      procedure SelectAll;
    end;
    

    I have a bunch of custom controls derived from standard VCL controls. They each implement this interface. When a clipboard operation reaches one of my forms it looks to see if the active control supports this interface and, if so, dispatches the appropriate method.

    For a very simple interface you can do this with an of object event handler, but once it gets sufficiently complex an interface works well. In fact I think that is a very good analogue. Use an interface where you a single of object event won't fit the functionality.

    0 讨论(0)
  • 2021-01-31 18:17

    Beyond what others already listed, a big pro of interfaces is the ability of aggregating them.

    I wrote a blog post on that topic a while ago which can be found here: http://www.nexusdb.com/support/index.php?q=intf-aggregation (tl;dr: you can have multiple objects each implementing an interface and then assemble them into an aggregate which to the outside world looks like a single object implementing all these interfaces)

    You might also want to have a look at the "Interface Fundamentals" and "Advanced Interface Usage and Patterns" posts linked there.

    0 讨论(0)
  • 2021-01-31 18:20

    All I say is that interfaces WITHOUT reference counting are VERY HIGH on my wishlist for delphi!!!

    --> The real use of interfaces is the declaration of an interface. Not the ability for reference counting!

    0 讨论(0)
提交回复
热议问题