再寫一個簡單的測試用例(Test Case):
TTestNumbericSerialNumberGenerator
1procedure TTestNumbericSerialNumberGenerator.SetUp;
2begin
3 fGenerator := TNumbericSerialNumberGenerator.Create('001', '999');
4end;
5
6procedure TTestNumbericSerialNumberGenerator.TestNextSerialNumber;
7begin
9 CheckEquals('002', fGenerator.NextSerialNumber('001'));
10 CheckEquals('010', fGenerator.NextSerialNumber('009'));
11 CheckEquals('011', fGenerator.NextSerialNumber('010'));
12 CheckEquals('100', fGenerator.NextSerialNumber('099'));
13 CheckEquals('999', fGenerator.NextSerialNumber('998'));
14 CheckEquals('001', fGenerator.NextSerialNumber('999'));
運行Test Case,編譯器提示TNumbericSerialNumberGenerator沒有定義,我們一起來實現它:
TNumbericSerialNumberGenerator Class Interface
1TNumbericSerialNumberGenerator =class(TInterfacedObject, ISerialNumberGenerator)
2private
3 fBeginSerialNumber, fEndSerialNumber: string;
4 fLength: Integer;
5 public
6 constructor Create(const beginSerialNumber, endSerialNumber: string);
7 function NextSerialNumber(const serialNumber: string): string;
8 function Validate(const serialNumber: string): Boolean;
9end
TNumbericSerialNumberGenerator
1constructor TNumbericSerialNumberGenerator.Create(const beginSerialNumber, endSerialNumber: string);
2begin
3 inherited Create;
4 fBeginSerialNumber := beginSerialNumber;
5 fEndSerialNumber := endSerialNumber;
6 fTotalLength := Length(beginSerialNumber);
7end;
8
9function TNumbericSerialNumberGenerator.NextSerialNumber(
10 const serialNumber: string): string;
11var
12 value: Int64;
13 repeated: Boolean;
14begin
15 CheckSerialNumber(serialNumber);
16 repeated := serialNumber = fEndSerialNumber;
17 if repeated then
18 begin
19 Result := fBeginSerialNumber;
20 end
21 else
22 begin
23 value := StrToInt64(serialNumber);
24 Inc(value);
25 Result := IntToStr(value);
26 Result := StringOfChar('0', fTotalLength - Length(Result)) + Result;
27 end;
28end;
29
30function TNumbericSerialNumberGenerator.Validate(
31 const serialNumber: string): Boolean;
32var
33 i: Integer;
34begin
35 Result := False;
36 if Length(serialNumber) = fTotalLength then
37 begin
38 for i :=1to fTotalLength do
39 begin
40 ifnot (AnsiChar(serialNumber[i]) in ['0'..'9']) then
41 begin
42 Break;
43 end;
44 end;
45 Result := True;
46 end;
47end;