Using implements for delegation

Many classes have properties that are subobjects. You can also use interfaces as property types. When a property is of an interface type (or a class type that implements the methods of an interface) you can use the keyword implements to specify that the methods of that interface are delegated to the object or interface reference which is the value of the property. The delegate only needs to provide implementation for the methods. It does not have to declare the interface support. The class containing the property must include the interface in its ancestor list.

By default, using the implements keyword delegates all interface methods. However, you can use methods resolution clauses or declare methods in your class that implement some of the interface methods to override this default behavior.

The following example uses the implements keyword in the design of a color adapter object that converts an 8-bit RGB color value to a Color reference:

unit cadapt;

interface type

IRGB8bit = interface

['{1d76360a-f4f5-11d1-87d4-00c04fb17199}'] function Red: Byte; function Green: Byte; function Blue: Byte; end;

IColorRef = interface

  • 1d76360b-f4f5-11d1-87d4-00c04fb17199}'] function Color: Integer; end;
  • TRGB8ColorRefAdapter map an IRGB8bit to an IColorRef } TRGB8ColorRefAdapter = class(TInterfacedObject, IRGB8bit, IColorRef) private FRGB8bit: IRGB8bit; FPalRelative: Boolean; public constructor Create(rgb: IRGB8bit);

property RGB8Intf: IRGB8bit read FRGB8bit implements IRGB8bit; property PalRelative: Boolean read FPalRelative write FPalRelative; function Color: Integer; end; implementation constructor TRGB8ColorRefAdapter.Create(rgb: IRGB8bit); begin

function TRGB8ColorRefAdapter.Color: Integer; begin if FPalRelative then

Result := PaletteRGB(RGB8Intf.Red, RGB8Intf.Green, RGB8Intf.Blue) else

Result := RGB(RGB8Intf.Red, RGB8Intf.Green, RGB8Intf.Blue);

For more information about the syntax, implementation details, and language rules of the implements keyword, see the Delphi Language Guide.

0 0

Post a comment

  • Receive news updates via email from this site