The wrapper design pattern can modify the interface of one class to the interface required by another class, and then allow classes that would otherwise be incompatible with the interface to work together.
In Delphi, in order for two classes to support the same interface, they must have the same ancestor class in order to achieve polymorphism when other classes call. But sometimes we want two classes that don't have a relationship to work together, the wrapper design pattern allows one class wrap part of another class to be part of the interface (which, of course, can be all, depending on the specific needs), thus simulating a multiple-inheritance relationship of a class similar to "uses".
Let's take a look at an example where a class tsimple inherits from TObject, but we want to put tsimple this class on the Delphi Control Panel (component palette), but we know that if a class can be placed on the control Panel, This class must be derived from tcomponent. Now we don't want to put tsimple on the control panel when we change Tsimple ancestor class TObject (for example, we don't have tsimple source code), we can build a tcomponent class that inherits from Tsimplewapper, Wrap the Tsimple interface in the Tsimplewapper class. Here is the example code for this sample:
type
TSample = class (TObject)
private
FSomeValue: Integer;
public
function SomeAction(const Data: string): Boolean;
property SomeValue: Integer read FSomeValue write FSomeValue;
end;
TSampleWrapper = class(TComponent)
private
FSample: TSample;
public
property Sample: TSample read FSample;
end;
Then we can implement the Tsample interface in the Tsample class with the following code:
TSampleWrapper = class (TComponent)
private
FSample: TSample;
protected
function GetSomeValue: Integer;
procedure SetSomeValue(Value: Integer);
public
function SomeAction(const Data: string): Boolean;
property Sample: TSample read FSample;
property SomeValue: Integer read GetSomeValue write SetSomeValue;
The interface implementation code is as follows:
function TSampleWrapper.GetSomeValue: Integer;
begin
Result := Sample.SomeValue;
end;
procedure TSampleWrapper.SetSomeValue(Value: Integer);
begin
Sample.SomeValue := Value;
end;
function TSampleWrapper.SomeAction(const Data: string): Boolean;
begin
Result := Sample.SomeAction(Data);
end;