unit EditGuardian;
interface
uses
System.Generics.Collections,
System.Classes, System.SysUtils,
Vcl.StdCtrls;
type
TEditMemento =
class( TPersistent )
private
FSelStart: Integer;
FSelLength: Integer;
FText:
string;
procedure AssignFromCustomEdit( ASource: TCustomEdit );
procedure AssignToCustomEdit( ADest: TCustomEdit );
procedure AssignToEditMemento( ADest: TEditMemento );
protected
procedure AssignTo( Dest: TPersistent );
override;
public
procedure Assign( Source: TPersistent );
override;
end;
TEditGuardian =
class
private
FEdit: TCustomEdit;
FMemento: TEditMemento;
FValidator: TPredicate<
string>;
public
constructor Create( AEdit: TCustomEdit; AValidator: TPredicate<
string> );
destructor Destroy;
override;
procedure Validate;
end;
implementation
{ TEditMemento }
procedure TEditMemento.Assign( Source: TPersistent );
begin
if Source
is TCustomEdit
then
AssignFromCustomEdit( Source
as TCustomEdit )
else
inherited;
end;
procedure TEditMemento.AssignFromCustomEdit( ASource: TCustomEdit );
begin
Self.FText := ASource.Text;
Self.FSelStart := ASource.SelStart;
Self.FSelLength := ASource.SelLength;
end;
procedure TEditMemento.AssignTo( Dest: TPersistent );
begin
if Dest
is TCustomEdit
then
AssignToCustomEdit( Dest
as TCustomEdit )
else if Dest
is TEditMemento
then
AssignToEditMemento( Dest
as TEditMemento )
else
inherited;
end;
procedure TEditMemento.AssignToCustomEdit( ADest: TCustomEdit );
begin
ADest.Text := Self.FText;
ADest.SelStart := Self.FSelStart;
ADest.SelLength := Self.FSelLength;
end;
procedure TEditMemento.AssignToEditMemento( ADest: TEditMemento );
begin
ADest.FText := Self.FText;
ADest.FSelStart := Self.FSelStart;
ADest.FSelLength := Self.FSelLength;
end;
{ TEditGuardian }
constructor TEditGuardian.Create( AEdit: TCustomEdit; AValidator: TPredicate<
string> );
begin
inherited Create;
if not Assigned( AEdit )
then
raise EArgumentNilException.Create( '
AEdit' );
if not Assigned( AValidator )
then
raise EArgumentNilException.Create( '
AValidator' );
FEdit := AEdit;
FMemento := TEditMemento.Create;
FValidator := AValidator;
Validate;
end;
destructor TEditGuardian.Destroy;
begin
FMemento.Free;
inherited;
end;
procedure TEditGuardian.Validate;
begin
if ( FEdit.Text = '
' )
or FValidator( FEdit.Text )
then
FMemento.Assign( FEdit )
else
FEdit.Assign( FMemento );
end;
end.