我們來看看客戶是如何使用這個模型的:
Code
1 procedure TTestNumberRule.TestCompositeNumber;
2 begin
3 fRule.AddCode('RK')
4 .AddLetters
5 .AddDigits('001', '999');
6 CheckEquals('RKA002', fRule.GetNextNumber('RKA001'));
7 CheckEquals('RKA999', fRule.GetNextNumber('RKA998'));
8 CheckEquals('RKB001', fRule.GetNextNumber('RKA999'));
9 CheckEquals('RKZ999', fRule.GetNextNumber('RKZ998'));
10 end;
11
12 procedure TTestNumberRule.TestDate;
13 begin
14 fRule.AddCode('RK')
15 .AddDateTime('YYYYMM', Self) // TTestNumberRule類實現了IDateTimeProvider接口,返回fDateTime便於測試
16 .AddDigits('0001', '9999');
17
18 fDateTime := EncodeDate(2009, 1, 1);
19 CheckEquals('RK2009010002', fRule.GetNextNumber('RK2009010001'));
20
21 fDateTime := EncodeDate(2009, 2, 1);
22 CheckEquals('RK2009020001', fRule.GetNextNumber('RK2009010999'));
23 end
(呵呵,現在是不是感覺NumberRule比之前的SerialNumberGenerator貼切多了?)
接下來我們再簡單看看TNumberRule的實現:
1. 設置規則
Code
1 function TNumberRule.AddCode(const code: string): TNumberRule;
2 begin
3 fParts.Add(TCodeNumberPart.Create(code));
4 Result := Self;
5 end;
6
7 function TNumberRule.AddDigits(const first,
8 last: string): TNumberRule;
9 begin
10 Result := AddSequence('0123456789', Length(first), first, last);
11 end;
12
13 function TNumberRule.AddLetters: TNumberRule;
14 begin
15 Result := AddSequence('ABCDEFGHIJKLMNOPQRSTUVWXYZ', 1, 'A', 'Z');
16 end;
17
18 function TNumberRule.AddDateTime(const format: string): TNumberRule;
19 begin
20 Result := AddDateTime(format, TCurrentDateTimeProvider.Create);
21 end;
22
23 function TNumberRule.AddDateTime(const format: string; const provider: IDateTimeProvider): TNumberRule;
24 begin
25 fParts.Add(TDateTimeNumberPart.Create(format, provider));
26 Result := Self;
27 end;
28
29 function TNumberRule.AddSequence(const dictionary: string; len: Integer;
30 const first, last: string): TNumberRule;
31 begin
32 fParts.Add(TSequenceNumberPart.Create(dictionary, len, first, last));
33 Result := Self;
34 end