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

前端 未结 9 1569
既然无缘
既然无缘 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.

提交回复
热议问题