|
| 1 | +====== |
| 2 | +Logger |
| 3 | +====== |
| 4 | + |
| 5 | +---------------- |
| 6 | +Public Interface |
| 7 | +---------------- |
| 8 | + |
| 9 | +* :ada:`Logger` uses a file for writing |
| 10 | +* :ada:`limited` cannot be copied, or compared |
| 11 | +* :ada:`procedure Put_Line` for logging |
| 12 | + |
| 13 | +.. code:: Ada |
| 14 | +
|
| 15 | + type Logger (Filename : not null access constant String) |
| 16 | + is tagged limited private; |
| 17 | +
|
| 18 | + procedure Put_Line |
| 19 | + (L : Logger; S : String); |
| 20 | +
|
| 21 | +---------------------------- |
| 22 | +Implementation: Private part |
| 23 | +---------------------------- |
| 24 | + |
| 25 | +.. code:: Ada |
| 26 | +
|
| 27 | + type Logger (Filename : not null access constant String) |
| 28 | + is new Ada.Finalization.Limited_Controlled with |
| 29 | +
|
| 30 | +.. note:: |
| 31 | + |
| 32 | + * :ada:`Limited_Controlled` |
| 33 | + * Maintains a handle to the log file |
| 34 | + |
| 35 | +.. code:: Ada |
| 36 | +
|
| 37 | + record |
| 38 | + Logfile : Ada.Text_IO.File_Type; |
| 39 | + end record; |
| 40 | +
|
| 41 | + procedure Initialize (L : in out Logger); |
| 42 | + -- opens the file |
| 43 | + procedure Finalize (L : in out Logger); |
| 44 | + -- closes the file |
| 45 | +
|
| 46 | +-------------------- |
| 47 | +Implementation: Body |
| 48 | +-------------------- |
| 49 | + |
| 50 | +* Trivial |
| 51 | + |
| 52 | +.. tip:: |
| 53 | + |
| 54 | + Once the hard part of designing the interface is done, implementation is trivial. |
| 55 | + |
| 56 | +.. code:: Ada |
| 57 | +
|
| 58 | + with Ada.Text_IO; use Ada.Text_IO; |
| 59 | +
|
| 60 | + package body Loggers is |
| 61 | + procedure Initialize (L : in out Logger) is |
| 62 | + begin |
| 63 | + Create (L.Logfile, Out_File, L.Filename.all); |
| 64 | + Put_Line (L, "Starting"); |
| 65 | + end Initialize; |
| 66 | +
|
| 67 | + procedure Put_Line (L : Logger; S : String) is |
| 68 | + begin |
| 69 | + Put_Line ("Logger: " & S); |
| 70 | + Put_Line (L.Logfile, S); |
| 71 | + end Put_Line; |
| 72 | +
|
| 73 | + procedure Finalize |
| 74 | + (L : in out Logger) is |
| 75 | + begin |
| 76 | + Put_Line (L, "Closing"); |
| 77 | + Close (L.Logfile); |
| 78 | + end Finalize; |
| 79 | + end Loggers; |
0 commit comments