Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- unit Unit2;
- interface
- uses
- System.Generics.Defaults,
- System.SysUtils;
- type
- ISwitch<T> = interface
- function &Case( const Value: T; AProc: TProc ): ISwitch<T>;
- procedure &Else( AProc: TProc );
- end;
- Switch = class abstract
- public
- class function &With<T>( const Value: T; const AComparer: IEqualityComparer<T> = nil ): ISwitch<T>; static;
- end;
- TSwitch<T> = class( TINterfacedObject, ISwitch<T> )
- private
- FMatched : Boolean;
- FValue : T;
- FComparer: IEqualityComparer<T>;
- protected
- function &Case( const Value: T; AProc: TProc ): ISwitch<T>;
- procedure &Else( AProc: TProc );
- public
- constructor Create( const Value: T; const AComparer: IEqualityComparer<T> );
- end;
- implementation
- { TSwitch<T> }
- function TSwitch<T>.&Case( const Value: T; AProc: TProc ): ISwitch<T>;
- begin
- if not FMatched and FComparer.Equals( Value, FValue )
- then
- begin
- FMatched := True;
- AProc( );
- end;
- Result := Self;
- end;
- constructor TSwitch<T>.Create( const Value: T; const AComparer: IEqualityComparer<T> );
- begin
- inherited Create;
- FValue := Value;
- if not Assigned( AComparer )
- then
- FComparer := TEqualityComparer<T>.Default
- else
- FComparer := AComparer;
- end;
- procedure TSwitch<T>.&Else( AProc: TProc );
- begin
- if not FMatched
- then
- AProc( );
- end;
- { Switch }
- class function Switch.&With<T>( const Value: T; const AComparer: IEqualityComparer<T> ): ISwitch<T>;
- begin
- Result := TSwitch<T>.Create( Value, AComparer );
- end;
- end.
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement