Advertisement
SirRufo

Switch

Mar 2nd, 2016
85
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Delphi 1.55 KB | None | 0 0
  1. unit Unit2;
  2.  
  3. interface
  4.  
  5. uses
  6.   System.Generics.Defaults,
  7.   System.SysUtils;
  8.  
  9. type
  10.   ISwitch<T> = interface
  11.     function &Case( const Value: T; AProc: TProc ): ISwitch<T>;
  12.     procedure &Else( AProc: TProc );
  13.   end;
  14.  
  15.   Switch = class abstract
  16.   public
  17.     class function &With<T>( const Value: T; const AComparer: IEqualityComparer<T> = nil ): ISwitch<T>; static;
  18.   end;
  19.  
  20.   TSwitch<T> = class( TINterfacedObject, ISwitch<T> )
  21.   private
  22.     FMatched : Boolean;
  23.     FValue   : T;
  24.     FComparer: IEqualityComparer<T>;
  25.   protected
  26.     function &Case( const Value: T; AProc: TProc ): ISwitch<T>;
  27.     procedure &Else( AProc: TProc );
  28.   public
  29.     constructor Create( const Value: T; const AComparer: IEqualityComparer<T> );
  30.   end;
  31.  
  32. implementation
  33.  
  34. { TSwitch<T> }
  35.  
  36. function TSwitch<T>.&Case( const Value: T; AProc: TProc ): ISwitch<T>;
  37. begin
  38.   if not FMatched and FComparer.Equals( Value, FValue )
  39.   then
  40.     begin
  41.       FMatched := True;
  42.       AProc( );
  43.     end;
  44.   Result := Self;
  45. end;
  46.  
  47. constructor TSwitch<T>.Create( const Value: T; const AComparer: IEqualityComparer<T> );
  48. begin
  49.   inherited Create;
  50.   FValue := Value;
  51.   if not Assigned( AComparer )
  52.   then
  53.     FComparer := TEqualityComparer<T>.Default
  54.   else
  55.     FComparer := AComparer;
  56. end;
  57.  
  58. procedure TSwitch<T>.&Else( AProc: TProc );
  59. begin
  60.   if not FMatched
  61.   then
  62.     AProc( );
  63. end;
  64.  
  65. { Switch }
  66.  
  67. class function Switch.&With<T>( const Value: T; const AComparer: IEqualityComparer<T> ): ISwitch<T>;
  68. begin
  69.   Result := TSwitch<T>.Create( Value, AComparer );
  70. end;
  71.  
  72. end.
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement