https://wiki.freepascal.org/api.php?action=feedcontributions&user=Amedeo&feedformat=atomFree Pascal wiki - User contributions [en]2024-03-28T15:57:18ZUser contributionsMediaWiki 1.35.6https://wiki.freepascal.org/index.php?title=Object_Oriented_Programming_with_Free_Pascal_and_Lazarus/it&diff=34782Object Oriented Programming with Free Pascal and Lazarus/it2009-04-01T12:11:34Z<p>Amedeo: /* Methods */</p>
<hr />
<div>{{Object_Oriented_Programming_with_FreePascal_and_Lazarus}}<br />
<br />
Esistono molte guide eccellenti su Pascal, ma questa guida tenta di coinvolgere ulteriormente il principiante , nella programmazione orientata agli oggetti o [[Glossary#OO | Object-Oriented Programming]], che è un'estensione dello standard pascal, offerta da Turbo pascal, Delphi e FreePascal/Lazarus.<br />
<br />
Un [[Glossary#Object | Object]] è un'estensione della struttura standard pascal detta [http://wiki.lazarus.freepascal.org/Record record]<br />
<br />
La programmazione Pascal in testo standard è adatta alla creazione di applicazioni che, come le applicazioni Unix tradizionali,sono adatte per fare una cosa e per farla molto bene.<br />
<br />
Ciò che un programma fa può essere un'azione veramente complicata ,e può offrire all'utente molte opzioni di menu,<br />
ma è essenzialmente ristretta ad obbedire a comandi che l'utente digita da tastiera e a listare le sue risposte sul terminale o sulla stampante. <br />
<br />
Per poter produrre una [[Glossary#GUI | Graphical User Interface (GUI)]] usualmente si utilizza una sorta di Metodo di programmazione orientata agli oggetti (spesso facendo uso di [[Glossary#C Programming Language | C]] o di una delle sue varianti, o Visual Basic, o una delle [[Glossary#OO | OO]] varianti di Pascal quali [[Glossary#FreePascal | FreePascal]] con o senza [[Glossary#Lazarus | Lazarus]]). <br />
<br />
In una GUI all'utente vengono presentate schermate con un gran numero di immagini organizzate in modo strutturato, consistenti in un'insieme di strumenti o [[Glossary#Widget | Widgets]] che sono associati con varie azioni quali <br />
*selezioni da menu, <br />
*aperture o salvataggio files , <br />
*connessioni ad Internet, <br />
*esecuzioni di calcoli numerici, etc. <br />
<br />
L'utente dovrà muovere il mouse o qualche altro puntatore o strumento sullo schermo, per selezionare le azioni che saranno eseguite in risposta al click del mouse o ai tasti premuti.<br />
<br />
I sistemi per offrire una complessa interfaccia grafica possono essere scritti in Pascal standard o quasi qualsiasi altro linguaggio di programmazione, ma è molto più facile l'utilizzo di un sistema orientato agli oggetti, in cui ogni oggetto grafico sullo schermo può avere tutte le sue proprietà e le sue procedure e funzioni connesse con il suo uso conglobate in una struttura comune.<br />
<br />
<br />
== Oggetti - una analogia con il mondo reale == <br />
Consideriamo le analogie di un campione di sangue prelevato in un ospedale o in uno studio medico.<br />
=== Campione di sangue ===<br />
Il campione fisico è certamente un oggetto o '''object'''; ed ha , associato con esso una quantità di informazioni,documenti ed altri oggetti fisici. <br />
<br />
*'''Provetta''', del tipo determinato dal test che si dovrà eseguire.<br />
<br />
*'''Metodica''' (o ''metodo'', ''procedura operativa standard'') utilizzata dall'infermiera o dal tecnico di laboratorio che prelevano e processano il campione <br />
** che tipo di provetta si dovrà usare, <br />
**come processare il campione<br />
**come conservarlo prima di consegnarlo al laboratorio. <br />
<br />
*'''Etichetta''' sulla provetta con i dettagli per <br />
**identificare il campione <br />
**Nome e cognome e data di nascita del paziente <br />
** data e ora del prelievo <br />
** analisi richieste. <br />
<br />
*'''Modulo di richiesta''' che accompagna il campione per il laboratorio cui il campione è diretto <br />
** ID Campione<br />
**ID del medico richiedente<br />
** quali analisi il medico richiede e <br />
**anamnesi e dettagli completi del paziente<br />
**La possibile diagnosi di cui si richiede conferma. <br />
<br />
<br />
Una copia delle richiesta viene conservata nella cartella clinica per ricordare al medico di attendersi risultati entro un periodo di tempo adeguato. <br />
<br />
<br />
*In laboratorio - '''metodi locali''' per determinare <br />
**come il campione deve essere analizzato, <br />
**Quale strumento usare, <br />
**come lo strumento dovrà operare e come dovrà essere calibrato, <br />
**come il risultato dovrà essere memorizzato formattato e <br />
**presentato al medico. <br />
<br />
L'effettivo'' 'risultato''' è un dato che il medico usa per formulare la diagnosi, e una copia dei risultati è archiviata nella cartella clinica del paziente.<br />
<br />
Il campione fisico può essere conservato per riferimento,per test di conferma o ulteriori test, o potrà essere smaltito in ottemperanza alle norme per lo smaltimento dei campioni biologici o mediante incenerimento, ci sarà un metodo per descrivere questo procedimento.<br />
<br />
<br />
Non è necessario che il medico dica tutti i dettagli operativi e le istruzioni di lavoro ogni qualvolta che un campione viene prelevato; anzi,egli può avere ben poche conoscenze di come il campione verrà processato dal laboratorio. <br />
<br />
I dettagli dei vari processi sono'' '''ereditati''' dai precedenti processi dei campione in analisi ,ossia a priori si è stabilito il metodo di processo del campione - ci sarà un piano generico per l'intera sequenza, e insieme abbiamo potuto pensare al campione di sangue,a tutti i suoi documenti e dati, e la metodica di base, come a un complesso'' 'oggetto'''.<br />
<br />
<br />
<br />
Nella mente del medico, il campione di sangue è visto come un'unica entità, come i suoi risultati, e per gli infermieri e tecnici il campione, la provetta, l'etichetta e le condizioni di conservazione anch'esse sono identificate come se fossero una sola entità.<br />
<br />
Traduzione da completare.....<br />
<br />
=== Un'altro esempio- Automobile ===<br />
Se non vi piace l'esempio del campione di sangue,lo stesso tipo di ragionamento può essere applicato all'automobile consegnata al garage per una riparazione.<br />
Ciò potrebbe consistere in<br />
*Il veicolo fisico<br />
*i documenti in possesso del proprietario: Libretto di circolazione (comprese targhe), le assicurazioni, le ricevute per l'acquisto, i pezzi di ricambio, le riparazioni, ecc<br />
*il consumo di carburante<br />
*i conducenti autorizzati ad utilizzare il veicolo, con le loro patenti di guida<br />
*gli interventi di manutenzione registrati presso il garage<br />
*metodi o procedure da seguire per la verifica e la manutenzione di routine<br />
*metodi da seguire per le riparazioni non di routine, ecc<br />
*informazioni di fatturazione per il cliente<br />
<br />
== Esempi di programmazione ==<br />
<br />
Basta con questa introduzione, fatta di esempi del mondo reale! Dobbiamo procedere con l'obiettivo principale: la programmazione FreePascal<br />
<br />
<br />
<br />
Dobbiamo considerare la creazione di un semplice modulo con pochi controlli per una applicazione in FreePascal / Lazzaro.<br />
<br />
<div class="floatleft">[[Image:ObjectInspector-TForm.png]]</div><br />
<div class="floatright">[[Image:BlankForm.png]]</div><br />
<br />
<br />
Richiamando la IDE di Lazarus, al programmatore viene presentato un modello vuoto "Form" in progettazione, in cui egli dovrà porre oggetti e vari controlli.<br />
<br />
Si noti che il Form vuoto precostituito è già un oggetto, con le proprie caratteristiche, come la posizione (in alto e sinistra), le dimensioni (altezza e larghezza), il colore, il font di default per l'aggiunta di testo ecc<br />
<br />
<br />
<br />
----<br />
<br />
<br />
Se un controllo Button, un tasto, viene immesso sul Form (tipo TButton), questi avrà una serie di proprietà, che possono essere esaminate nella finestra Object Inspector .<br />
<br />
<br />
Molte delle proprietà hanno nomi simili a quelle del Modulo 'Form', questo è dovuto al fatto che molte proprietà sono'' 'ereditate''' da parte di alcuni comuni antenati di classe, che definiscono le proprietà come sono definite e gestite dalle classi discendenti. <br />
<br />
Così come per le proprietà, l'Object Inspector offre una scheda denominata'' 'Eventi''', che dà accesso ai gestori di eventi 'Event Handlers' che sono metodi per gestire tali eventi, come un clic del mouse su un pulsante (OnClick) o alcuni cambiamento di posizione, le dimensioni o altre proprietà (OnChange).<br />
<br />
L'immagine fisica del pulsante nel Modulo o Form, insieme con tutte le sue proprietà e metodi di gestione, dovrebbe essere considerato come una singola entità o'' 'oggetto''' in Pascal.<br />
<br />
<div class="floatleft">[[Image:ObjectInspector-TButton.png]]</div><br />
<div class="floatright">[[Image:FormWithButton.png]]</div><br />
<div class="floatright">[[Image:Source_FormWithButton1.png ]]</div><br />
<br />
== Object-Oriented Extensions to standard Pascal ==<br />
<br />
La struttura Pascal di tipo record viene estesa per definire un<br />
=== Object ===<br />
<br />
Un oggetto è uno speciale tipo di record. Il record contiene tutti i campi che sono dichiarati nella definizione dell'oggetto (proprio come un convenzionale record), ma ora le procedure e le funzioni possono essere dichiarate come se fossero parte del record e si richiamano come puntatori ai metodi associati con il tipo di oggetto.<br />
<br />
Ad esempio, un oggetto può contenere una serie di valori reali, una matrice,unitamente con un metodo di calcolo della media.<br />
<br />
Type<br />
Average = Object<br />
NumVal: Integer;<br />
Values: Array [1..200] of Real;<br />
Function Mean: Real; { calculates the average value of the array }<br />
End;<br />
<br />
Gli oggetti possono "ereditare" campi e metodi da oggetti "madre". Ciò significa che questi campi e metodi possono essere usati come se fossero incluse negli oggetti dichiarati come un oggetto figlio.<br />
<br />
Inoltre, viene introdotto un concetto di visibilità : i campi, le procedure e le funzioni possono essere dichiarati come pubblici, protetti o privati. Per impostazione predefinita, i campi e metodi sono pubblici, e possono essere esportati al di fuori delle attuali unit. Campi o metodi protetti sono disponibili solo per gli oggetti discendenti dal corrente oggetto antenato. Campi e metodi dichiarati privati sono unicamente accessibili nella unit corrente:<br />
il loro scopo è limitato all'implementazione della corrente unit.<br />
<br />
=== Class ===<br />
Gli oggetti molto spesso non sono usati da se stessi in FreePascal and Lazarus; invece le classi sono largamente usate.<br />
La Classe è definita quasi alla stessa stregua di un oggetto, ma è un puntatore ad un oggetto piuttosto che l'oggetto stesso.<br />
<br />
Tecnicamente, questo significa che la classe è assegnata "on the Heap of a program", mentre l'oggetto viene assegnato in Stack.<br />
Ecco un semplice esempio di dichiarazione di una classe:<br />
<br />
{-----------------------------------------}<br />
{example of Class declaration from the LCL}<br />
{-----------------------------------------}<br />
TPen = class(TFPCustomPen)<br />
private<br />
FColor: TColor;<br />
FPenHandleCached: boolean;<br />
FReference: TWSPenReference;<br />
procedure FreeReference;<br />
function GetHandle: HPEN;<br />
function GetReference: TWSPenReference;<br />
procedure ReferenceNeeded;<br />
procedure SetHandle(const Value: HPEN);<br />
protected<br />
procedure DoAllocateResources; override;<br />
procedure DoDeAllocateResources; override;<br />
procedure DoCopyProps(From: TFPCanvasHelper); override;<br />
procedure SetColor<br />
(const NewColor: TColor; const NewFPColor: TFPColor); virtual;<br />
procedure SetFPColor(const AValue: TFPColor); override;<br />
procedure SetColor(Value: TColor);<br />
procedure SetMode(Value: TPenMode); override;<br />
procedure SetStyle(Value: TPenStyle); override;<br />
procedure SetWidth(value: Integer); override;<br />
public<br />
constructor Create; override;<br />
destructor Destroy; override;<br />
procedure Assign(Source: TPersistent); override;<br />
property Handle: HPEN read GetHandle write SetHandle; deprecated;<br />
property Reference: TWSPenReference read GetReference;<br />
published<br />
property Color: TColor read FColor write SetColor default clBlack;<br />
property Mode default pmCopy;<br />
property Style default psSolid;<br />
property Width default 1;<br />
end;<br />
<br />
<br />
Si noti che questa classe è definita come un istanza di un altra classe '''madre''' o '''antenato''' (''''TFPCustomPen) da cui '''eredita''' tutte le sue proprietà e metodi.Ha alcuni campi propri, raggruppati sotto <br />
*'''private''' - questo significa che gli elementi qui definiti, sono disponibili o visibili da altre classi procedure o funzioni definite all'interno della stessa unit di programma (questo esempio è da'' Graphics'', così che una qualsiasi delle altre classi, come ''TBitMap'',''TPicture'' etc nella stessa unità è in grado di farne uso.Esse sono generalmente variabili locali (eg ''FColor'', ''FPenHandleCached'') o metodi usati localmente(''GetHandle'', ''SetHandle'') ma possono essere usate o possono riferirvi voci dichiarate in sezioni '''protected''' or '''public'''. <br />
*'''protected''' - questo significa che le voci definite qui sono solo disponibili o visibili da classi che discendono da quella classe '''antenata''',ed eredita le sue proprietà o metodi<br />
*'''public''' - questo significa che le voci definite qui sono solo disponibili per qualunque unit che includa la unit corrente in essa con la clausula [[Glossary#Uses | Uses]] <br />
*'''published''' - è simile alla sezione '''public''', ma il compilatore genera anche il tipo di informazioni che è necessario per lo streaming automatico di queste classi. Spesso la lista delle voci appare nel Object Inspector di Lazarus; se non compare una lista '''published''',tutti i campi '''public''' appaiono normalmente in the Object Inspector.<br />
<br />
=== Methods ===<br />
Un metodo è esattamente come una procedura standard o una funzione, ma può avere qualche '''directives'''.<br />
<br />
Alcuni dei metodi di definizione di cui sopra sono etichettati con la direttiva '''virtual'''; altri sono etichettati con la direttiva '''override'''.<br />
*'''virtual''' significa che il tipo o il grado effettivo di un metodo non è noto al momento della compilazione,ma è stato selezionato in run-time a seconda di ciò che effettivamente richiama il sotto-programma sul momento. It could be considered a place-holder in the definition of the class.<br />
*'''override''' means that at run-time the locally given definition can take the place of a definition inherited from an ancestor class, particularly if it was '''virtual'''. If you particularly want to use the method defined in the ancestor class, it is sometimes necessary to call it specifically with the '''inherited''' clause.<br />
<br />
Methods with no virtual or override directive are '''static''' methods (the usual kind in Pascal). Those with a virtual or override directive are '''dynamic'''.<br />
<br />
Special instances of methods are:<br />
*'''create''' - a '''constructor''' for a class, which takes care of allocating memory, collecting together all the information needed and configuring/initializing the various properties.<br />
*'''destroy''' - a '''destructor''' for a class, which removes all the parts of the class from the system in an orderly and logical way, and returns all its resources for the system to re-use.<br />
<br />
=== Properties ===<br />
<br />
Properties are just like ordinary fields in a conventional Pascal record, but they can have '''read''' and/or '''write''' specifiers.<br />
*'''read''' specifier is a field, or a function that returns a result of the correct type for the property. In the example above, the property ''Color'' has a read specifier ''FColor'', which is a local variable containing the value to be used. If a property has a '''read''' but no '''write''' specifier, it is read-only.<br />
*'''write''' specifier is a field, or a procedure that will store the value of the property in a specific location. In the example above, ''Color'' has a write specifier ''SetColor'' that is a procedure (defined in the '''protected''' section) for writing the color value to some specified location. If a property has a '''write''' but no '''read''' specifier, it is write-only.<br />
*'''default''' - note that it is possible to set a '''default''' value for a property. For example, ''Color'' here is given the default value ''clBlack'', or black, at the time of creation. It could subsequently be given a different value, by a programming assignment statement, or in the Object Inspector.<br />
<br />
== Further information ==<br />
<br />
This has only scratched the surface of the topic. For more details, readers are strongly recommended to read the [http://lazarus-ccr.sourceforge.net/fpcdoc/ref/ref.html FreePascal] manuals, especially Chapters 5 ('''Objects''') and 6 ('''Classes''')<br />
<br />
--[[User:Kirkpatc|Kirkpatc]] 11:04, 20 July 2008 (CEST)<br />
<br />
----<br />
[[Console Mode Pascal]]</div>Amedeohttps://wiki.freepascal.org/index.php?title=Object_Oriented_Programming_with_Free_Pascal_and_Lazarus/it&diff=34781Object Oriented Programming with Free Pascal and Lazarus/it2009-04-01T11:54:15Z<p>Amedeo: /* Class */</p>
<hr />
<div>{{Object_Oriented_Programming_with_FreePascal_and_Lazarus}}<br />
<br />
Esistono molte guide eccellenti su Pascal, ma questa guida tenta di coinvolgere ulteriormente il principiante , nella programmazione orientata agli oggetti o [[Glossary#OO | Object-Oriented Programming]], che è un'estensione dello standard pascal, offerta da Turbo pascal, Delphi e FreePascal/Lazarus.<br />
<br />
Un [[Glossary#Object | Object]] è un'estensione della struttura standard pascal detta [http://wiki.lazarus.freepascal.org/Record record]<br />
<br />
La programmazione Pascal in testo standard è adatta alla creazione di applicazioni che, come le applicazioni Unix tradizionali,sono adatte per fare una cosa e per farla molto bene.<br />
<br />
Ciò che un programma fa può essere un'azione veramente complicata ,e può offrire all'utente molte opzioni di menu,<br />
ma è essenzialmente ristretta ad obbedire a comandi che l'utente digita da tastiera e a listare le sue risposte sul terminale o sulla stampante. <br />
<br />
Per poter produrre una [[Glossary#GUI | Graphical User Interface (GUI)]] usualmente si utilizza una sorta di Metodo di programmazione orientata agli oggetti (spesso facendo uso di [[Glossary#C Programming Language | C]] o di una delle sue varianti, o Visual Basic, o una delle [[Glossary#OO | OO]] varianti di Pascal quali [[Glossary#FreePascal | FreePascal]] con o senza [[Glossary#Lazarus | Lazarus]]). <br />
<br />
In una GUI all'utente vengono presentate schermate con un gran numero di immagini organizzate in modo strutturato, consistenti in un'insieme di strumenti o [[Glossary#Widget | Widgets]] che sono associati con varie azioni quali <br />
*selezioni da menu, <br />
*aperture o salvataggio files , <br />
*connessioni ad Internet, <br />
*esecuzioni di calcoli numerici, etc. <br />
<br />
L'utente dovrà muovere il mouse o qualche altro puntatore o strumento sullo schermo, per selezionare le azioni che saranno eseguite in risposta al click del mouse o ai tasti premuti.<br />
<br />
I sistemi per offrire una complessa interfaccia grafica possono essere scritti in Pascal standard o quasi qualsiasi altro linguaggio di programmazione, ma è molto più facile l'utilizzo di un sistema orientato agli oggetti, in cui ogni oggetto grafico sullo schermo può avere tutte le sue proprietà e le sue procedure e funzioni connesse con il suo uso conglobate in una struttura comune.<br />
<br />
<br />
== Oggetti - una analogia con il mondo reale == <br />
Consideriamo le analogie di un campione di sangue prelevato in un ospedale o in uno studio medico.<br />
=== Campione di sangue ===<br />
Il campione fisico è certamente un oggetto o '''object'''; ed ha , associato con esso una quantità di informazioni,documenti ed altri oggetti fisici. <br />
<br />
*'''Provetta''', del tipo determinato dal test che si dovrà eseguire.<br />
<br />
*'''Metodica''' (o ''metodo'', ''procedura operativa standard'') utilizzata dall'infermiera o dal tecnico di laboratorio che prelevano e processano il campione <br />
** che tipo di provetta si dovrà usare, <br />
**come processare il campione<br />
**come conservarlo prima di consegnarlo al laboratorio. <br />
<br />
*'''Etichetta''' sulla provetta con i dettagli per <br />
**identificare il campione <br />
**Nome e cognome e data di nascita del paziente <br />
** data e ora del prelievo <br />
** analisi richieste. <br />
<br />
*'''Modulo di richiesta''' che accompagna il campione per il laboratorio cui il campione è diretto <br />
** ID Campione<br />
**ID del medico richiedente<br />
** quali analisi il medico richiede e <br />
**anamnesi e dettagli completi del paziente<br />
**La possibile diagnosi di cui si richiede conferma. <br />
<br />
<br />
Una copia delle richiesta viene conservata nella cartella clinica per ricordare al medico di attendersi risultati entro un periodo di tempo adeguato. <br />
<br />
<br />
*In laboratorio - '''metodi locali''' per determinare <br />
**come il campione deve essere analizzato, <br />
**Quale strumento usare, <br />
**come lo strumento dovrà operare e come dovrà essere calibrato, <br />
**come il risultato dovrà essere memorizzato formattato e <br />
**presentato al medico. <br />
<br />
L'effettivo'' 'risultato''' è un dato che il medico usa per formulare la diagnosi, e una copia dei risultati è archiviata nella cartella clinica del paziente.<br />
<br />
Il campione fisico può essere conservato per riferimento,per test di conferma o ulteriori test, o potrà essere smaltito in ottemperanza alle norme per lo smaltimento dei campioni biologici o mediante incenerimento, ci sarà un metodo per descrivere questo procedimento.<br />
<br />
<br />
Non è necessario che il medico dica tutti i dettagli operativi e le istruzioni di lavoro ogni qualvolta che un campione viene prelevato; anzi,egli può avere ben poche conoscenze di come il campione verrà processato dal laboratorio. <br />
<br />
I dettagli dei vari processi sono'' '''ereditati''' dai precedenti processi dei campione in analisi ,ossia a priori si è stabilito il metodo di processo del campione - ci sarà un piano generico per l'intera sequenza, e insieme abbiamo potuto pensare al campione di sangue,a tutti i suoi documenti e dati, e la metodica di base, come a un complesso'' 'oggetto'''.<br />
<br />
<br />
<br />
Nella mente del medico, il campione di sangue è visto come un'unica entità, come i suoi risultati, e per gli infermieri e tecnici il campione, la provetta, l'etichetta e le condizioni di conservazione anch'esse sono identificate come se fossero una sola entità.<br />
<br />
Traduzione da completare.....<br />
<br />
=== Un'altro esempio- Automobile ===<br />
Se non vi piace l'esempio del campione di sangue,lo stesso tipo di ragionamento può essere applicato all'automobile consegnata al garage per una riparazione.<br />
Ciò potrebbe consistere in<br />
*Il veicolo fisico<br />
*i documenti in possesso del proprietario: Libretto di circolazione (comprese targhe), le assicurazioni, le ricevute per l'acquisto, i pezzi di ricambio, le riparazioni, ecc<br />
*il consumo di carburante<br />
*i conducenti autorizzati ad utilizzare il veicolo, con le loro patenti di guida<br />
*gli interventi di manutenzione registrati presso il garage<br />
*metodi o procedure da seguire per la verifica e la manutenzione di routine<br />
*metodi da seguire per le riparazioni non di routine, ecc<br />
*informazioni di fatturazione per il cliente<br />
<br />
== Esempi di programmazione ==<br />
<br />
Basta con questa introduzione, fatta di esempi del mondo reale! Dobbiamo procedere con l'obiettivo principale: la programmazione FreePascal<br />
<br />
<br />
<br />
Dobbiamo considerare la creazione di un semplice modulo con pochi controlli per una applicazione in FreePascal / Lazzaro.<br />
<br />
<div class="floatleft">[[Image:ObjectInspector-TForm.png]]</div><br />
<div class="floatright">[[Image:BlankForm.png]]</div><br />
<br />
<br />
Richiamando la IDE di Lazarus, al programmatore viene presentato un modello vuoto "Form" in progettazione, in cui egli dovrà porre oggetti e vari controlli.<br />
<br />
Si noti che il Form vuoto precostituito è già un oggetto, con le proprie caratteristiche, come la posizione (in alto e sinistra), le dimensioni (altezza e larghezza), il colore, il font di default per l'aggiunta di testo ecc<br />
<br />
<br />
<br />
----<br />
<br />
<br />
Se un controllo Button, un tasto, viene immesso sul Form (tipo TButton), questi avrà una serie di proprietà, che possono essere esaminate nella finestra Object Inspector .<br />
<br />
<br />
Molte delle proprietà hanno nomi simili a quelle del Modulo 'Form', questo è dovuto al fatto che molte proprietà sono'' 'ereditate''' da parte di alcuni comuni antenati di classe, che definiscono le proprietà come sono definite e gestite dalle classi discendenti. <br />
<br />
Così come per le proprietà, l'Object Inspector offre una scheda denominata'' 'Eventi''', che dà accesso ai gestori di eventi 'Event Handlers' che sono metodi per gestire tali eventi, come un clic del mouse su un pulsante (OnClick) o alcuni cambiamento di posizione, le dimensioni o altre proprietà (OnChange).<br />
<br />
L'immagine fisica del pulsante nel Modulo o Form, insieme con tutte le sue proprietà e metodi di gestione, dovrebbe essere considerato come una singola entità o'' 'oggetto''' in Pascal.<br />
<br />
<div class="floatleft">[[Image:ObjectInspector-TButton.png]]</div><br />
<div class="floatright">[[Image:FormWithButton.png]]</div><br />
<div class="floatright">[[Image:Source_FormWithButton1.png ]]</div><br />
<br />
== Object-Oriented Extensions to standard Pascal ==<br />
<br />
La struttura Pascal di tipo record viene estesa per definire un<br />
=== Object ===<br />
<br />
Un oggetto è uno speciale tipo di record. Il record contiene tutti i campi che sono dichiarati nella definizione dell'oggetto (proprio come un convenzionale record), ma ora le procedure e le funzioni possono essere dichiarate come se fossero parte del record e si richiamano come puntatori ai metodi associati con il tipo di oggetto.<br />
<br />
Ad esempio, un oggetto può contenere una serie di valori reali, una matrice,unitamente con un metodo di calcolo della media.<br />
<br />
Type<br />
Average = Object<br />
NumVal: Integer;<br />
Values: Array [1..200] of Real;<br />
Function Mean: Real; { calculates the average value of the array }<br />
End;<br />
<br />
Gli oggetti possono "ereditare" campi e metodi da oggetti "madre". Ciò significa che questi campi e metodi possono essere usati come se fossero incluse negli oggetti dichiarati come un oggetto figlio.<br />
<br />
Inoltre, viene introdotto un concetto di visibilità : i campi, le procedure e le funzioni possono essere dichiarati come pubblici, protetti o privati. Per impostazione predefinita, i campi e metodi sono pubblici, e possono essere esportati al di fuori delle attuali unit. Campi o metodi protetti sono disponibili solo per gli oggetti discendenti dal corrente oggetto antenato. Campi e metodi dichiarati privati sono unicamente accessibili nella unit corrente:<br />
il loro scopo è limitato all'implementazione della corrente unit.<br />
<br />
=== Class ===<br />
Gli oggetti molto spesso non sono usati da se stessi in FreePascal and Lazarus; invece le classi sono largamente usate.<br />
La Classe è definita quasi alla stessa stregua di un oggetto, ma è un puntatore ad un oggetto piuttosto che l'oggetto stesso.<br />
<br />
Tecnicamente, questo significa che la classe è assegnata "on the Heap of a program", mentre l'oggetto viene assegnato in Stack.<br />
Ecco un semplice esempio di dichiarazione di una classe:<br />
<br />
{-----------------------------------------}<br />
{example of Class declaration from the LCL}<br />
{-----------------------------------------}<br />
TPen = class(TFPCustomPen)<br />
private<br />
FColor: TColor;<br />
FPenHandleCached: boolean;<br />
FReference: TWSPenReference;<br />
procedure FreeReference;<br />
function GetHandle: HPEN;<br />
function GetReference: TWSPenReference;<br />
procedure ReferenceNeeded;<br />
procedure SetHandle(const Value: HPEN);<br />
protected<br />
procedure DoAllocateResources; override;<br />
procedure DoDeAllocateResources; override;<br />
procedure DoCopyProps(From: TFPCanvasHelper); override;<br />
procedure SetColor<br />
(const NewColor: TColor; const NewFPColor: TFPColor); virtual;<br />
procedure SetFPColor(const AValue: TFPColor); override;<br />
procedure SetColor(Value: TColor);<br />
procedure SetMode(Value: TPenMode); override;<br />
procedure SetStyle(Value: TPenStyle); override;<br />
procedure SetWidth(value: Integer); override;<br />
public<br />
constructor Create; override;<br />
destructor Destroy; override;<br />
procedure Assign(Source: TPersistent); override;<br />
property Handle: HPEN read GetHandle write SetHandle; deprecated;<br />
property Reference: TWSPenReference read GetReference;<br />
published<br />
property Color: TColor read FColor write SetColor default clBlack;<br />
property Mode default pmCopy;<br />
property Style default psSolid;<br />
property Width default 1;<br />
end;<br />
<br />
<br />
Si noti che questa classe è definita come un istanza di un altra classe '''madre''' o '''antenato''' (''''TFPCustomPen) da cui '''eredita''' tutte le sue proprietà e metodi.Ha alcuni campi propri, raggruppati sotto <br />
*'''private''' - questo significa che gli elementi qui definiti, sono disponibili o visibili da altre classi procedure o funzioni definite all'interno della stessa unit di programma (questo esempio è da'' Graphics'', così che una qualsiasi delle altre classi, come ''TBitMap'',''TPicture'' etc nella stessa unità è in grado di farne uso.Esse sono generalmente variabili locali (eg ''FColor'', ''FPenHandleCached'') o metodi usati localmente(''GetHandle'', ''SetHandle'') ma possono essere usate o possono riferirvi voci dichiarate in sezioni '''protected''' or '''public'''. <br />
*'''protected''' - questo significa che le voci definite qui sono solo disponibili o visibili da classi che discendono da quella classe '''antenata''',ed eredita le sue proprietà o metodi<br />
*'''public''' - questo significa che le voci definite qui sono solo disponibili per qualunque unit che includa la unit corrente in essa con la clausula [[Glossary#Uses | Uses]] <br />
*'''published''' - è simile alla sezione '''public''', ma il compilatore genera anche il tipo di informazioni che è necessario per lo streaming automatico di queste classi. Spesso la lista delle voci appare nel Object Inspector di Lazarus; se non compare una lista '''published''',tutti i campi '''public''' appaiono normalmente in the Object Inspector.<br />
<br />
=== Methods ===<br />
A method is just like a standard procedure or function, but can have some additional '''directives'''.<br />
<br />
Some of the methods defined above are labelled with the directive '''virtual'''; others are labelled with the '''override''' directive.<br />
*'''virtual''' means that the type or actual instance of a method is not known at compile-time, but is selected at run-time depending on what sub-program actually calls the method. It could be considered a place-holder in the definition of the class.<br />
*'''override''' means that at run-time the locally given definition can take the place of a definition inherited from an ancestor class, particularly if it was '''virtual'''. If you particularly want to use the method defined in the ancestor class, it is sometimes necessary to call it specifically with the '''inherited''' clause.<br />
<br />
Methods with no virtual or override directive are '''static''' methods (the usual kind in Pascal). Those with a virtual or override directive are '''dynamic'''.<br />
<br />
Special instances of methods are:<br />
*'''create''' - a '''constructor''' for a class, which takes care of allocating memory, collecting together all the information needed and configuring/initializing the various properties.<br />
*'''destroy''' - a '''destructor''' for a class, which removes all the parts of the class from the system in an orderly and logical way, and returns all its resources for the system to re-use.<br />
<br />
=== Properties ===<br />
<br />
Properties are just like ordinary fields in a conventional Pascal record, but they can have '''read''' and/or '''write''' specifiers.<br />
*'''read''' specifier is a field, or a function that returns a result of the correct type for the property. In the example above, the property ''Color'' has a read specifier ''FColor'', which is a local variable containing the value to be used. If a property has a '''read''' but no '''write''' specifier, it is read-only.<br />
*'''write''' specifier is a field, or a procedure that will store the value of the property in a specific location. In the example above, ''Color'' has a write specifier ''SetColor'' that is a procedure (defined in the '''protected''' section) for writing the color value to some specified location. If a property has a '''write''' but no '''read''' specifier, it is write-only.<br />
*'''default''' - note that it is possible to set a '''default''' value for a property. For example, ''Color'' here is given the default value ''clBlack'', or black, at the time of creation. It could subsequently be given a different value, by a programming assignment statement, or in the Object Inspector.<br />
<br />
== Further information ==<br />
<br />
This has only scratched the surface of the topic. For more details, readers are strongly recommended to read the [http://lazarus-ccr.sourceforge.net/fpcdoc/ref/ref.html FreePascal] manuals, especially Chapters 5 ('''Objects''') and 6 ('''Classes''')<br />
<br />
--[[User:Kirkpatc|Kirkpatc]] 11:04, 20 July 2008 (CEST)<br />
<br />
----<br />
[[Console Mode Pascal]]</div>Amedeohttps://wiki.freepascal.org/index.php?title=Object_Oriented_Programming_with_Free_Pascal_and_Lazarus/it&diff=34778Object Oriented Programming with Free Pascal and Lazarus/it2009-04-01T10:47:57Z<p>Amedeo: /* Class */</p>
<hr />
<div>{{Object_Oriented_Programming_with_FreePascal_and_Lazarus}}<br />
<br />
Esistono molte guide eccellenti su Pascal, ma questa guida tenta di coinvolgere ulteriormente il principiante , nella programmazione orientata agli oggetti o [[Glossary#OO | Object-Oriented Programming]], che è un'estensione dello standard pascal, offerta da Turbo pascal, Delphi e FreePascal/Lazarus.<br />
<br />
Un [[Glossary#Object | Object]] è un'estensione della struttura standard pascal detta [http://wiki.lazarus.freepascal.org/Record record]<br />
<br />
La programmazione Pascal in testo standard è adatta alla creazione di applicazioni che, come le applicazioni Unix tradizionali,sono adatte per fare una cosa e per farla molto bene.<br />
<br />
Ciò che un programma fa può essere un'azione veramente complicata ,e può offrire all'utente molte opzioni di menu,<br />
ma è essenzialmente ristretta ad obbedire a comandi che l'utente digita da tastiera e a listare le sue risposte sul terminale o sulla stampante. <br />
<br />
Per poter produrre una [[Glossary#GUI | Graphical User Interface (GUI)]] usualmente si utilizza una sorta di Metodo di programmazione orientata agli oggetti (spesso facendo uso di [[Glossary#C Programming Language | C]] o di una delle sue varianti, o Visual Basic, o una delle [[Glossary#OO | OO]] varianti di Pascal quali [[Glossary#FreePascal | FreePascal]] con o senza [[Glossary#Lazarus | Lazarus]]). <br />
<br />
In una GUI all'utente vengono presentate schermate con un gran numero di immagini organizzate in modo strutturato, consistenti in un'insieme di strumenti o [[Glossary#Widget | Widgets]] che sono associati con varie azioni quali <br />
*selezioni da menu, <br />
*aperture o salvataggio files , <br />
*connessioni ad Internet, <br />
*esecuzioni di calcoli numerici, etc. <br />
<br />
L'utente dovrà muovere il mouse o qualche altro puntatore o strumento sullo schermo, per selezionare le azioni che saranno eseguite in risposta al click del mouse o ai tasti premuti.<br />
<br />
I sistemi per offrire una complessa interfaccia grafica possono essere scritti in Pascal standard o quasi qualsiasi altro linguaggio di programmazione, ma è molto più facile l'utilizzo di un sistema orientato agli oggetti, in cui ogni oggetto grafico sullo schermo può avere tutte le sue proprietà e le sue procedure e funzioni connesse con il suo uso conglobate in una struttura comune.<br />
<br />
<br />
== Oggetti - una analogia con il mondo reale == <br />
Consideriamo le analogie di un campione di sangue prelevato in un ospedale o in uno studio medico.<br />
=== Campione di sangue ===<br />
Il campione fisico è certamente un oggetto o '''object'''; ed ha , associato con esso una quantità di informazioni,documenti ed altri oggetti fisici. <br />
<br />
*'''Provetta''', del tipo determinato dal test che si dovrà eseguire.<br />
<br />
*'''Metodica''' (o ''metodo'', ''procedura operativa standard'') utilizzata dall'infermiera o dal tecnico di laboratorio che prelevano e processano il campione <br />
** che tipo di provetta si dovrà usare, <br />
**come processare il campione<br />
**come conservarlo prima di consegnarlo al laboratorio. <br />
<br />
*'''Etichetta''' sulla provetta con i dettagli per <br />
**identificare il campione <br />
**Nome e cognome e data di nascita del paziente <br />
** data e ora del prelievo <br />
** analisi richieste. <br />
<br />
*'''Modulo di richiesta''' che accompagna il campione per il laboratorio cui il campione è diretto <br />
** ID Campione<br />
**ID del medico richiedente<br />
** quali analisi il medico richiede e <br />
**anamnesi e dettagli completi del paziente<br />
**La possibile diagnosi di cui si richiede conferma. <br />
<br />
<br />
Una copia delle richiesta viene conservata nella cartella clinica per ricordare al medico di attendersi risultati entro un periodo di tempo adeguato. <br />
<br />
<br />
*In laboratorio - '''metodi locali''' per determinare <br />
**come il campione deve essere analizzato, <br />
**Quale strumento usare, <br />
**come lo strumento dovrà operare e come dovrà essere calibrato, <br />
**come il risultato dovrà essere memorizzato formattato e <br />
**presentato al medico. <br />
<br />
L'effettivo'' 'risultato''' è un dato che il medico usa per formulare la diagnosi, e una copia dei risultati è archiviata nella cartella clinica del paziente.<br />
<br />
Il campione fisico può essere conservato per riferimento,per test di conferma o ulteriori test, o potrà essere smaltito in ottemperanza alle norme per lo smaltimento dei campioni biologici o mediante incenerimento, ci sarà un metodo per descrivere questo procedimento.<br />
<br />
<br />
Non è necessario che il medico dica tutti i dettagli operativi e le istruzioni di lavoro ogni qualvolta che un campione viene prelevato; anzi,egli può avere ben poche conoscenze di come il campione verrà processato dal laboratorio. <br />
<br />
I dettagli dei vari processi sono'' '''ereditati''' dai precedenti processi dei campione in analisi ,ossia a priori si è stabilito il metodo di processo del campione - ci sarà un piano generico per l'intera sequenza, e insieme abbiamo potuto pensare al campione di sangue,a tutti i suoi documenti e dati, e la metodica di base, come a un complesso'' 'oggetto'''.<br />
<br />
<br />
<br />
Nella mente del medico, il campione di sangue è visto come un'unica entità, come i suoi risultati, e per gli infermieri e tecnici il campione, la provetta, l'etichetta e le condizioni di conservazione anch'esse sono identificate come se fossero una sola entità.<br />
<br />
Traduzione da completare.....<br />
<br />
=== Un'altro esempio- Automobile ===<br />
Se non vi piace l'esempio del campione di sangue,lo stesso tipo di ragionamento può essere applicato all'automobile consegnata al garage per una riparazione.<br />
Ciò potrebbe consistere in<br />
*Il veicolo fisico<br />
*i documenti in possesso del proprietario: Libretto di circolazione (comprese targhe), le assicurazioni, le ricevute per l'acquisto, i pezzi di ricambio, le riparazioni, ecc<br />
*il consumo di carburante<br />
*i conducenti autorizzati ad utilizzare il veicolo, con le loro patenti di guida<br />
*gli interventi di manutenzione registrati presso il garage<br />
*metodi o procedure da seguire per la verifica e la manutenzione di routine<br />
*metodi da seguire per le riparazioni non di routine, ecc<br />
*informazioni di fatturazione per il cliente<br />
<br />
== Esempi di programmazione ==<br />
<br />
Basta con questa introduzione, fatta di esempi del mondo reale! Dobbiamo procedere con l'obiettivo principale: la programmazione FreePascal<br />
<br />
<br />
<br />
Dobbiamo considerare la creazione di un semplice modulo con pochi controlli per una applicazione in FreePascal / Lazzaro.<br />
<br />
<div class="floatleft">[[Image:ObjectInspector-TForm.png]]</div><br />
<div class="floatright">[[Image:BlankForm.png]]</div><br />
<br />
<br />
Richiamando la IDE di Lazarus, al programmatore viene presentato un modello vuoto "Form" in progettazione, in cui egli dovrà porre oggetti e vari controlli.<br />
<br />
Si noti che il Form vuoto precostituito è già un oggetto, con le proprie caratteristiche, come la posizione (in alto e sinistra), le dimensioni (altezza e larghezza), il colore, il font di default per l'aggiunta di testo ecc<br />
<br />
<br />
<br />
----<br />
<br />
<br />
Se un controllo Button, un tasto, viene immesso sul Form (tipo TButton), questi avrà una serie di proprietà, che possono essere esaminate nella finestra Object Inspector .<br />
<br />
<br />
Molte delle proprietà hanno nomi simili a quelle del Modulo 'Form', questo è dovuto al fatto che molte proprietà sono'' 'ereditate''' da parte di alcuni comuni antenati di classe, che definiscono le proprietà come sono definite e gestite dalle classi discendenti. <br />
<br />
Così come per le proprietà, l'Object Inspector offre una scheda denominata'' 'Eventi''', che dà accesso ai gestori di eventi 'Event Handlers' che sono metodi per gestire tali eventi, come un clic del mouse su un pulsante (OnClick) o alcuni cambiamento di posizione, le dimensioni o altre proprietà (OnChange).<br />
<br />
L'immagine fisica del pulsante nel Modulo o Form, insieme con tutte le sue proprietà e metodi di gestione, dovrebbe essere considerato come una singola entità o'' 'oggetto''' in Pascal.<br />
<br />
<div class="floatleft">[[Image:ObjectInspector-TButton.png]]</div><br />
<div class="floatright">[[Image:FormWithButton.png]]</div><br />
<div class="floatright">[[Image:Source_FormWithButton1.png ]]</div><br />
<br />
== Object-Oriented Extensions to standard Pascal ==<br />
<br />
La struttura Pascal di tipo record viene estesa per definire un<br />
=== Object ===<br />
<br />
Un oggetto è uno speciale tipo di record. Il record contiene tutti i campi che sono dichiarati nella definizione dell'oggetto (proprio come un convenzionale record), ma ora le procedure e le funzioni possono essere dichiarate come se fossero parte del record e si richiamano come puntatori ai metodi associati con il tipo di oggetto.<br />
<br />
Ad esempio, un oggetto può contenere una serie di valori reali, una matrice,unitamente con un metodo di calcolo della media.<br />
<br />
Type<br />
Average = Object<br />
NumVal: Integer;<br />
Values: Array [1..200] of Real;<br />
Function Mean: Real; { calculates the average value of the array }<br />
End;<br />
<br />
Gli oggetti possono "ereditare" campi e metodi da oggetti "madre". Ciò significa che questi campi e metodi possono essere usati come se fossero incluse negli oggetti dichiarati come un oggetto figlio.<br />
<br />
Inoltre, viene introdotto un concetto di visibilità : i campi, le procedure e le funzioni possono essere dichiarati come pubblici, protetti o privati. Per impostazione predefinita, i campi e metodi sono pubblici, e possono essere esportati al di fuori delle attuali unit. Campi o metodi protetti sono disponibili solo per gli oggetti discendenti dal corrente oggetto antenato. Campi e metodi dichiarati privati sono unicamente accessibili nella unit corrente:<br />
il loro scopo è limitato all'implementazione della corrente unit.<br />
<br />
=== Class ===<br />
Gli oggetti molto spesso non sono usati da se stessi in FreePascal and Lazarus; invece le classi sono largamente usate.<br />
La Classe è definita quasi alla stessa stregua di un oggetto, ma è un puntatore ad un oggetto piuttosto che l'oggetto stesso.<br />
<br />
Tecnicamente, questo significa che la classe è assegnata "on the Heap of a program", mentre l'oggetto viene assegnato in Stack.<br />
Ecco un semplice esempio di dichiarazione di una classe:<br />
<br />
{-----------------------------------------}<br />
{example of Class declaration from the LCL}<br />
{-----------------------------------------}<br />
TPen = class(TFPCustomPen)<br />
private<br />
FColor: TColor;<br />
FPenHandleCached: boolean;<br />
FReference: TWSPenReference;<br />
procedure FreeReference;<br />
function GetHandle: HPEN;<br />
function GetReference: TWSPenReference;<br />
procedure ReferenceNeeded;<br />
procedure SetHandle(const Value: HPEN);<br />
protected<br />
procedure DoAllocateResources; override;<br />
procedure DoDeAllocateResources; override;<br />
procedure DoCopyProps(From: TFPCanvasHelper); override;<br />
procedure SetColor<br />
(const NewColor: TColor; const NewFPColor: TFPColor); virtual;<br />
procedure SetFPColor(const AValue: TFPColor); override;<br />
procedure SetColor(Value: TColor);<br />
procedure SetMode(Value: TPenMode); override;<br />
procedure SetStyle(Value: TPenStyle); override;<br />
procedure SetWidth(value: Integer); override;<br />
public<br />
constructor Create; override;<br />
destructor Destroy; override;<br />
procedure Assign(Source: TPersistent); override;<br />
property Handle: HPEN read GetHandle write SetHandle; deprecated;<br />
property Reference: TWSPenReference read GetReference;<br />
published<br />
property Color: TColor read FColor write SetColor default clBlack;<br />
property Mode default pmCopy;<br />
property Style default psSolid;<br />
property Width default 1;<br />
end;<br />
<br />
<br />
Si noti che questa classe è definita come un istanza di un altra classe '''madre''' o '''antenato''' (''''TFPCustomPen) da cui '''eredita''' tutte le sue proprietà e metodi.Ha alcuni campi propri, raggruppati sotto <br />
*'''private''' - questo significa che gli elementi qui definiti, sono disponibili o visibili da altre classi procedure o funzioni definite all'interno della stessa unit di programma (questo esempio è da'' Graphics'', così che una qualsiasi delle altre classi, come ''TBitMap'',''TPicture'' etc nella stessa unità è in grado di farne uso.Esse sono generalmente variabili locali (eg ''FColor'', ''FPenHandleCached'') o metodi usati localmente(''GetHandle'', ''SetHandle'') ma possono essere usate o possono riferirvi voci dichiarate in sezioni '''protected''' or '''public'''. <br />
*'''protected''' - questo significa che le voci definite qui sono solo disponibili o visibili da classi che discendono da quella classe '''antenata''',ed eredita le sue proprietà o metodi<br />
*'''public''' - questo significa che le voci definite qui sono solo disponibili per qualunque unit che includa la unit corrente in essa con la clausula [[Glossary#Uses | Uses]] <br />
*'''published''' - is the same as a '''public''' section, but the compiler also generates type information that is needed for automatic streaming of these classes. Often the list of published items appear in the Object Inspector of Lazarus; if there is no '''published''' list, all the '''public''' fields usually appear in the Object Inspector.<br />
<br />
=== Methods ===<br />
A method is just like a standard procedure or function, but can have some additional '''directives'''.<br />
<br />
Some of the methods defined above are labelled with the directive '''virtual'''; others are labelled with the '''override''' directive.<br />
*'''virtual''' means that the type or actual instance of a method is not known at compile-time, but is selected at run-time depending on what sub-program actually calls the method. It could be considered a place-holder in the definition of the class.<br />
*'''override''' means that at run-time the locally given definition can take the place of a definition inherited from an ancestor class, particularly if it was '''virtual'''. If you particularly want to use the method defined in the ancestor class, it is sometimes necessary to call it specifically with the '''inherited''' clause.<br />
<br />
Methods with no virtual or override directive are '''static''' methods (the usual kind in Pascal). Those with a virtual or override directive are '''dynamic'''.<br />
<br />
Special instances of methods are:<br />
*'''create''' - a '''constructor''' for a class, which takes care of allocating memory, collecting together all the information needed and configuring/initializing the various properties.<br />
*'''destroy''' - a '''destructor''' for a class, which removes all the parts of the class from the system in an orderly and logical way, and returns all its resources for the system to re-use.<br />
<br />
=== Properties ===<br />
<br />
Properties are just like ordinary fields in a conventional Pascal record, but they can have '''read''' and/or '''write''' specifiers.<br />
*'''read''' specifier is a field, or a function that returns a result of the correct type for the property. In the example above, the property ''Color'' has a read specifier ''FColor'', which is a local variable containing the value to be used. If a property has a '''read''' but no '''write''' specifier, it is read-only.<br />
*'''write''' specifier is a field, or a procedure that will store the value of the property in a specific location. In the example above, ''Color'' has a write specifier ''SetColor'' that is a procedure (defined in the '''protected''' section) for writing the color value to some specified location. If a property has a '''write''' but no '''read''' specifier, it is write-only.<br />
*'''default''' - note that it is possible to set a '''default''' value for a property. For example, ''Color'' here is given the default value ''clBlack'', or black, at the time of creation. It could subsequently be given a different value, by a programming assignment statement, or in the Object Inspector.<br />
<br />
== Further information ==<br />
<br />
This has only scratched the surface of the topic. For more details, readers are strongly recommended to read the [http://lazarus-ccr.sourceforge.net/fpcdoc/ref/ref.html FreePascal] manuals, especially Chapters 5 ('''Objects''') and 6 ('''Classes''')<br />
<br />
--[[User:Kirkpatc|Kirkpatc]] 11:04, 20 July 2008 (CEST)<br />
<br />
----<br />
[[Console Mode Pascal]]</div>Amedeohttps://wiki.freepascal.org/index.php?title=Object_Oriented_Programming_with_Free_Pascal_and_Lazarus/it&diff=34777Object Oriented Programming with Free Pascal and Lazarus/it2009-04-01T10:46:49Z<p>Amedeo: /* Class */</p>
<hr />
<div>{{Object_Oriented_Programming_with_FreePascal_and_Lazarus}}<br />
<br />
Esistono molte guide eccellenti su Pascal, ma questa guida tenta di coinvolgere ulteriormente il principiante , nella programmazione orientata agli oggetti o [[Glossary#OO | Object-Oriented Programming]], che è un'estensione dello standard pascal, offerta da Turbo pascal, Delphi e FreePascal/Lazarus.<br />
<br />
Un [[Glossary#Object | Object]] è un'estensione della struttura standard pascal detta [http://wiki.lazarus.freepascal.org/Record record]<br />
<br />
La programmazione Pascal in testo standard è adatta alla creazione di applicazioni che, come le applicazioni Unix tradizionali,sono adatte per fare una cosa e per farla molto bene.<br />
<br />
Ciò che un programma fa può essere un'azione veramente complicata ,e può offrire all'utente molte opzioni di menu,<br />
ma è essenzialmente ristretta ad obbedire a comandi che l'utente digita da tastiera e a listare le sue risposte sul terminale o sulla stampante. <br />
<br />
Per poter produrre una [[Glossary#GUI | Graphical User Interface (GUI)]] usualmente si utilizza una sorta di Metodo di programmazione orientata agli oggetti (spesso facendo uso di [[Glossary#C Programming Language | C]] o di una delle sue varianti, o Visual Basic, o una delle [[Glossary#OO | OO]] varianti di Pascal quali [[Glossary#FreePascal | FreePascal]] con o senza [[Glossary#Lazarus | Lazarus]]). <br />
<br />
In una GUI all'utente vengono presentate schermate con un gran numero di immagini organizzate in modo strutturato, consistenti in un'insieme di strumenti o [[Glossary#Widget | Widgets]] che sono associati con varie azioni quali <br />
*selezioni da menu, <br />
*aperture o salvataggio files , <br />
*connessioni ad Internet, <br />
*esecuzioni di calcoli numerici, etc. <br />
<br />
L'utente dovrà muovere il mouse o qualche altro puntatore o strumento sullo schermo, per selezionare le azioni che saranno eseguite in risposta al click del mouse o ai tasti premuti.<br />
<br />
I sistemi per offrire una complessa interfaccia grafica possono essere scritti in Pascal standard o quasi qualsiasi altro linguaggio di programmazione, ma è molto più facile l'utilizzo di un sistema orientato agli oggetti, in cui ogni oggetto grafico sullo schermo può avere tutte le sue proprietà e le sue procedure e funzioni connesse con il suo uso conglobate in una struttura comune.<br />
<br />
<br />
== Oggetti - una analogia con il mondo reale == <br />
Consideriamo le analogie di un campione di sangue prelevato in un ospedale o in uno studio medico.<br />
=== Campione di sangue ===<br />
Il campione fisico è certamente un oggetto o '''object'''; ed ha , associato con esso una quantità di informazioni,documenti ed altri oggetti fisici. <br />
<br />
*'''Provetta''', del tipo determinato dal test che si dovrà eseguire.<br />
<br />
*'''Metodica''' (o ''metodo'', ''procedura operativa standard'') utilizzata dall'infermiera o dal tecnico di laboratorio che prelevano e processano il campione <br />
** che tipo di provetta si dovrà usare, <br />
**come processare il campione<br />
**come conservarlo prima di consegnarlo al laboratorio. <br />
<br />
*'''Etichetta''' sulla provetta con i dettagli per <br />
**identificare il campione <br />
**Nome e cognome e data di nascita del paziente <br />
** data e ora del prelievo <br />
** analisi richieste. <br />
<br />
*'''Modulo di richiesta''' che accompagna il campione per il laboratorio cui il campione è diretto <br />
** ID Campione<br />
**ID del medico richiedente<br />
** quali analisi il medico richiede e <br />
**anamnesi e dettagli completi del paziente<br />
**La possibile diagnosi di cui si richiede conferma. <br />
<br />
<br />
Una copia delle richiesta viene conservata nella cartella clinica per ricordare al medico di attendersi risultati entro un periodo di tempo adeguato. <br />
<br />
<br />
*In laboratorio - '''metodi locali''' per determinare <br />
**come il campione deve essere analizzato, <br />
**Quale strumento usare, <br />
**come lo strumento dovrà operare e come dovrà essere calibrato, <br />
**come il risultato dovrà essere memorizzato formattato e <br />
**presentato al medico. <br />
<br />
L'effettivo'' 'risultato''' è un dato che il medico usa per formulare la diagnosi, e una copia dei risultati è archiviata nella cartella clinica del paziente.<br />
<br />
Il campione fisico può essere conservato per riferimento,per test di conferma o ulteriori test, o potrà essere smaltito in ottemperanza alle norme per lo smaltimento dei campioni biologici o mediante incenerimento, ci sarà un metodo per descrivere questo procedimento.<br />
<br />
<br />
Non è necessario che il medico dica tutti i dettagli operativi e le istruzioni di lavoro ogni qualvolta che un campione viene prelevato; anzi,egli può avere ben poche conoscenze di come il campione verrà processato dal laboratorio. <br />
<br />
I dettagli dei vari processi sono'' '''ereditati''' dai precedenti processi dei campione in analisi ,ossia a priori si è stabilito il metodo di processo del campione - ci sarà un piano generico per l'intera sequenza, e insieme abbiamo potuto pensare al campione di sangue,a tutti i suoi documenti e dati, e la metodica di base, come a un complesso'' 'oggetto'''.<br />
<br />
<br />
<br />
Nella mente del medico, il campione di sangue è visto come un'unica entità, come i suoi risultati, e per gli infermieri e tecnici il campione, la provetta, l'etichetta e le condizioni di conservazione anch'esse sono identificate come se fossero una sola entità.<br />
<br />
Traduzione da completare.....<br />
<br />
=== Un'altro esempio- Automobile ===<br />
Se non vi piace l'esempio del campione di sangue,lo stesso tipo di ragionamento può essere applicato all'automobile consegnata al garage per una riparazione.<br />
Ciò potrebbe consistere in<br />
*Il veicolo fisico<br />
*i documenti in possesso del proprietario: Libretto di circolazione (comprese targhe), le assicurazioni, le ricevute per l'acquisto, i pezzi di ricambio, le riparazioni, ecc<br />
*il consumo di carburante<br />
*i conducenti autorizzati ad utilizzare il veicolo, con le loro patenti di guida<br />
*gli interventi di manutenzione registrati presso il garage<br />
*metodi o procedure da seguire per la verifica e la manutenzione di routine<br />
*metodi da seguire per le riparazioni non di routine, ecc<br />
*informazioni di fatturazione per il cliente<br />
<br />
== Esempi di programmazione ==<br />
<br />
Basta con questa introduzione, fatta di esempi del mondo reale! Dobbiamo procedere con l'obiettivo principale: la programmazione FreePascal<br />
<br />
<br />
<br />
Dobbiamo considerare la creazione di un semplice modulo con pochi controlli per una applicazione in FreePascal / Lazzaro.<br />
<br />
<div class="floatleft">[[Image:ObjectInspector-TForm.png]]</div><br />
<div class="floatright">[[Image:BlankForm.png]]</div><br />
<br />
<br />
Richiamando la IDE di Lazarus, al programmatore viene presentato un modello vuoto "Form" in progettazione, in cui egli dovrà porre oggetti e vari controlli.<br />
<br />
Si noti che il Form vuoto precostituito è già un oggetto, con le proprie caratteristiche, come la posizione (in alto e sinistra), le dimensioni (altezza e larghezza), il colore, il font di default per l'aggiunta di testo ecc<br />
<br />
<br />
<br />
----<br />
<br />
<br />
Se un controllo Button, un tasto, viene immesso sul Form (tipo TButton), questi avrà una serie di proprietà, che possono essere esaminate nella finestra Object Inspector .<br />
<br />
<br />
Molte delle proprietà hanno nomi simili a quelle del Modulo 'Form', questo è dovuto al fatto che molte proprietà sono'' 'ereditate''' da parte di alcuni comuni antenati di classe, che definiscono le proprietà come sono definite e gestite dalle classi discendenti. <br />
<br />
Così come per le proprietà, l'Object Inspector offre una scheda denominata'' 'Eventi''', che dà accesso ai gestori di eventi 'Event Handlers' che sono metodi per gestire tali eventi, come un clic del mouse su un pulsante (OnClick) o alcuni cambiamento di posizione, le dimensioni o altre proprietà (OnChange).<br />
<br />
L'immagine fisica del pulsante nel Modulo o Form, insieme con tutte le sue proprietà e metodi di gestione, dovrebbe essere considerato come una singola entità o'' 'oggetto''' in Pascal.<br />
<br />
<div class="floatleft">[[Image:ObjectInspector-TButton.png]]</div><br />
<div class="floatright">[[Image:FormWithButton.png]]</div><br />
<div class="floatright">[[Image:Source_FormWithButton1.png ]]</div><br />
<br />
== Object-Oriented Extensions to standard Pascal ==<br />
<br />
La struttura Pascal di tipo record viene estesa per definire un<br />
=== Object ===<br />
<br />
Un oggetto è uno speciale tipo di record. Il record contiene tutti i campi che sono dichiarati nella definizione dell'oggetto (proprio come un convenzionale record), ma ora le procedure e le funzioni possono essere dichiarate come se fossero parte del record e si richiamano come puntatori ai metodi associati con il tipo di oggetto.<br />
<br />
Ad esempio, un oggetto può contenere una serie di valori reali, una matrice,unitamente con un metodo di calcolo della media.<br />
<br />
Type<br />
Average = Object<br />
NumVal: Integer;<br />
Values: Array [1..200] of Real;<br />
Function Mean: Real; { calculates the average value of the array }<br />
End;<br />
<br />
Gli oggetti possono "ereditare" campi e metodi da oggetti "madre". Ciò significa che questi campi e metodi possono essere usati come se fossero incluse negli oggetti dichiarati come un oggetto figlio.<br />
<br />
Inoltre, viene introdotto un concetto di visibilità : i campi, le procedure e le funzioni possono essere dichiarati come pubblici, protetti o privati. Per impostazione predefinita, i campi e metodi sono pubblici, e possono essere esportati al di fuori delle attuali unit. Campi o metodi protetti sono disponibili solo per gli oggetti discendenti dal corrente oggetto antenato. Campi e metodi dichiarati privati sono unicamente accessibili nella unit corrente:<br />
il loro scopo è limitato all'implementazione della corrente unit.<br />
<br />
=== Class ===<br />
Gli oggetti molto spesso non sono usati da se stessi in FreePascal and Lazarus; invece le classi sono largamente usate.<br />
La Classe è definita quasi alla stessa stregua di un oggetto, ma è un puntatore ad un oggetto piuttosto che l'oggetto stesso.<br />
<br />
Tecnicamente, questo significa che la classe è assegnata "on the Heap of a program", mentre l'oggetto viene assegnato in Stack.<br />
Ecco un semplice esempio di dichiarazione di una classe:<br />
<br />
{-----------------------------------------}<br />
{example of Class declaration from the LCL}<br />
{-----------------------------------------}<br />
TPen = class(TFPCustomPen)<br />
private<br />
FColor: TColor;<br />
FPenHandleCached: boolean;<br />
FReference: TWSPenReference;<br />
procedure FreeReference;<br />
function GetHandle: HPEN;<br />
function GetReference: TWSPenReference;<br />
procedure ReferenceNeeded;<br />
procedure SetHandle(const Value: HPEN);<br />
protected<br />
procedure DoAllocateResources; override;<br />
procedure DoDeAllocateResources; override;<br />
procedure DoCopyProps(From: TFPCanvasHelper); override;<br />
procedure SetColor<br />
(const NewColor: TColor; const NewFPColor: TFPColor); virtual;<br />
procedure SetFPColor(const AValue: TFPColor); override;<br />
procedure SetColor(Value: TColor);<br />
procedure SetMode(Value: TPenMode); override;<br />
procedure SetStyle(Value: TPenStyle); override;<br />
procedure SetWidth(value: Integer); override;<br />
public<br />
constructor Create; override;<br />
destructor Destroy; override;<br />
procedure Assign(Source: TPersistent); override;<br />
property Handle: HPEN read GetHandle write SetHandle; deprecated;<br />
property Reference: TWSPenReference read GetReference;<br />
published<br />
property Color: TColor read FColor write SetColor default clBlack;<br />
property Mode default pmCopy;<br />
property Style default psSolid;<br />
property Width default 1;<br />
end;<br />
<br />
<br />
Si noti che questa classe è definita come un istanza di un altra classe '''madre''' o '''antenato''' (''''TFPCustomPen) da cui '''eredita''' tutte le sue proprietà e metodi.Ha alcuni campi propri, raggruppati sotto <br />
*'''private''' - questo significa che gli elementi qui definiti, sono disponibili o visibili da altre classi procedure o funzioni definite all'interno della stessa unit di programma (questo esempio è da'' Graphics'', così che una qualsiasi delle altre classi, come ''TBitMap'',''TPicture'' etc nella stessa unità è in grado di farne uso.<br />
Esse sono generalmente variabili locali (eg ''FColor'', ''FPenHandleCached'') o metodi usati localmente(''GetHandle'', ''SetHandle'') ma possono essere usate o possono riferirvi voci dichiarate in sezioni '''protected''' or '''public'''.<br />
*'''protected''' - questo significa che le voci definite qui sono solo disponibili o visibili da classi che discendono da quella classe '''antenata''',ed eredita le sue proprietà o metodi<br />
*'''public''' - questo significa che le voci definite qui sono solo disponibili per qualunque unit che includa la unit corrente in essa con la clausula [[Glossary#Uses | Uses]] <br />
*'''published''' - is the same as a '''public''' section, but the compiler also generates type information that is needed for automatic streaming of these classes. Often the list of published items appear in the Object Inspector of Lazarus; if there is no '''published''' list, all the '''public''' fields usually appear in the Object Inspector.<br />
<br />
=== Methods ===<br />
A method is just like a standard procedure or function, but can have some additional '''directives'''.<br />
<br />
Some of the methods defined above are labelled with the directive '''virtual'''; others are labelled with the '''override''' directive.<br />
*'''virtual''' means that the type or actual instance of a method is not known at compile-time, but is selected at run-time depending on what sub-program actually calls the method. It could be considered a place-holder in the definition of the class.<br />
*'''override''' means that at run-time the locally given definition can take the place of a definition inherited from an ancestor class, particularly if it was '''virtual'''. If you particularly want to use the method defined in the ancestor class, it is sometimes necessary to call it specifically with the '''inherited''' clause.<br />
<br />
Methods with no virtual or override directive are '''static''' methods (the usual kind in Pascal). Those with a virtual or override directive are '''dynamic'''.<br />
<br />
Special instances of methods are:<br />
*'''create''' - a '''constructor''' for a class, which takes care of allocating memory, collecting together all the information needed and configuring/initializing the various properties.<br />
*'''destroy''' - a '''destructor''' for a class, which removes all the parts of the class from the system in an orderly and logical way, and returns all its resources for the system to re-use.<br />
<br />
=== Properties ===<br />
<br />
Properties are just like ordinary fields in a conventional Pascal record, but they can have '''read''' and/or '''write''' specifiers.<br />
*'''read''' specifier is a field, or a function that returns a result of the correct type for the property. In the example above, the property ''Color'' has a read specifier ''FColor'', which is a local variable containing the value to be used. If a property has a '''read''' but no '''write''' specifier, it is read-only.<br />
*'''write''' specifier is a field, or a procedure that will store the value of the property in a specific location. In the example above, ''Color'' has a write specifier ''SetColor'' that is a procedure (defined in the '''protected''' section) for writing the color value to some specified location. If a property has a '''write''' but no '''read''' specifier, it is write-only.<br />
*'''default''' - note that it is possible to set a '''default''' value for a property. For example, ''Color'' here is given the default value ''clBlack'', or black, at the time of creation. It could subsequently be given a different value, by a programming assignment statement, or in the Object Inspector.<br />
<br />
== Further information ==<br />
<br />
This has only scratched the surface of the topic. For more details, readers are strongly recommended to read the [http://lazarus-ccr.sourceforge.net/fpcdoc/ref/ref.html FreePascal] manuals, especially Chapters 5 ('''Objects''') and 6 ('''Classes''')<br />
<br />
--[[User:Kirkpatc|Kirkpatc]] 11:04, 20 July 2008 (CEST)<br />
<br />
----<br />
[[Console Mode Pascal]]</div>Amedeohttps://wiki.freepascal.org/index.php?title=Object_Oriented_Programming_with_Free_Pascal_and_Lazarus/it&diff=34776Object Oriented Programming with Free Pascal and Lazarus/it2009-04-01T10:41:37Z<p>Amedeo: /* Class */</p>
<hr />
<div>{{Object_Oriented_Programming_with_FreePascal_and_Lazarus}}<br />
<br />
Esistono molte guide eccellenti su Pascal, ma questa guida tenta di coinvolgere ulteriormente il principiante , nella programmazione orientata agli oggetti o [[Glossary#OO | Object-Oriented Programming]], che è un'estensione dello standard pascal, offerta da Turbo pascal, Delphi e FreePascal/Lazarus.<br />
<br />
Un [[Glossary#Object | Object]] è un'estensione della struttura standard pascal detta [http://wiki.lazarus.freepascal.org/Record record]<br />
<br />
La programmazione Pascal in testo standard è adatta alla creazione di applicazioni che, come le applicazioni Unix tradizionali,sono adatte per fare una cosa e per farla molto bene.<br />
<br />
Ciò che un programma fa può essere un'azione veramente complicata ,e può offrire all'utente molte opzioni di menu,<br />
ma è essenzialmente ristretta ad obbedire a comandi che l'utente digita da tastiera e a listare le sue risposte sul terminale o sulla stampante. <br />
<br />
Per poter produrre una [[Glossary#GUI | Graphical User Interface (GUI)]] usualmente si utilizza una sorta di Metodo di programmazione orientata agli oggetti (spesso facendo uso di [[Glossary#C Programming Language | C]] o di una delle sue varianti, o Visual Basic, o una delle [[Glossary#OO | OO]] varianti di Pascal quali [[Glossary#FreePascal | FreePascal]] con o senza [[Glossary#Lazarus | Lazarus]]). <br />
<br />
In una GUI all'utente vengono presentate schermate con un gran numero di immagini organizzate in modo strutturato, consistenti in un'insieme di strumenti o [[Glossary#Widget | Widgets]] che sono associati con varie azioni quali <br />
*selezioni da menu, <br />
*aperture o salvataggio files , <br />
*connessioni ad Internet, <br />
*esecuzioni di calcoli numerici, etc. <br />
<br />
L'utente dovrà muovere il mouse o qualche altro puntatore o strumento sullo schermo, per selezionare le azioni che saranno eseguite in risposta al click del mouse o ai tasti premuti.<br />
<br />
I sistemi per offrire una complessa interfaccia grafica possono essere scritti in Pascal standard o quasi qualsiasi altro linguaggio di programmazione, ma è molto più facile l'utilizzo di un sistema orientato agli oggetti, in cui ogni oggetto grafico sullo schermo può avere tutte le sue proprietà e le sue procedure e funzioni connesse con il suo uso conglobate in una struttura comune.<br />
<br />
<br />
== Oggetti - una analogia con il mondo reale == <br />
Consideriamo le analogie di un campione di sangue prelevato in un ospedale o in uno studio medico.<br />
=== Campione di sangue ===<br />
Il campione fisico è certamente un oggetto o '''object'''; ed ha , associato con esso una quantità di informazioni,documenti ed altri oggetti fisici. <br />
<br />
*'''Provetta''', del tipo determinato dal test che si dovrà eseguire.<br />
<br />
*'''Metodica''' (o ''metodo'', ''procedura operativa standard'') utilizzata dall'infermiera o dal tecnico di laboratorio che prelevano e processano il campione <br />
** che tipo di provetta si dovrà usare, <br />
**come processare il campione<br />
**come conservarlo prima di consegnarlo al laboratorio. <br />
<br />
*'''Etichetta''' sulla provetta con i dettagli per <br />
**identificare il campione <br />
**Nome e cognome e data di nascita del paziente <br />
** data e ora del prelievo <br />
** analisi richieste. <br />
<br />
*'''Modulo di richiesta''' che accompagna il campione per il laboratorio cui il campione è diretto <br />
** ID Campione<br />
**ID del medico richiedente<br />
** quali analisi il medico richiede e <br />
**anamnesi e dettagli completi del paziente<br />
**La possibile diagnosi di cui si richiede conferma. <br />
<br />
<br />
Una copia delle richiesta viene conservata nella cartella clinica per ricordare al medico di attendersi risultati entro un periodo di tempo adeguato. <br />
<br />
<br />
*In laboratorio - '''metodi locali''' per determinare <br />
**come il campione deve essere analizzato, <br />
**Quale strumento usare, <br />
**come lo strumento dovrà operare e come dovrà essere calibrato, <br />
**come il risultato dovrà essere memorizzato formattato e <br />
**presentato al medico. <br />
<br />
L'effettivo'' 'risultato''' è un dato che il medico usa per formulare la diagnosi, e una copia dei risultati è archiviata nella cartella clinica del paziente.<br />
<br />
Il campione fisico può essere conservato per riferimento,per test di conferma o ulteriori test, o potrà essere smaltito in ottemperanza alle norme per lo smaltimento dei campioni biologici o mediante incenerimento, ci sarà un metodo per descrivere questo procedimento.<br />
<br />
<br />
Non è necessario che il medico dica tutti i dettagli operativi e le istruzioni di lavoro ogni qualvolta che un campione viene prelevato; anzi,egli può avere ben poche conoscenze di come il campione verrà processato dal laboratorio. <br />
<br />
I dettagli dei vari processi sono'' '''ereditati''' dai precedenti processi dei campione in analisi ,ossia a priori si è stabilito il metodo di processo del campione - ci sarà un piano generico per l'intera sequenza, e insieme abbiamo potuto pensare al campione di sangue,a tutti i suoi documenti e dati, e la metodica di base, come a un complesso'' 'oggetto'''.<br />
<br />
<br />
<br />
Nella mente del medico, il campione di sangue è visto come un'unica entità, come i suoi risultati, e per gli infermieri e tecnici il campione, la provetta, l'etichetta e le condizioni di conservazione anch'esse sono identificate come se fossero una sola entità.<br />
<br />
Traduzione da completare.....<br />
<br />
=== Un'altro esempio- Automobile ===<br />
Se non vi piace l'esempio del campione di sangue,lo stesso tipo di ragionamento può essere applicato all'automobile consegnata al garage per una riparazione.<br />
Ciò potrebbe consistere in<br />
*Il veicolo fisico<br />
*i documenti in possesso del proprietario: Libretto di circolazione (comprese targhe), le assicurazioni, le ricevute per l'acquisto, i pezzi di ricambio, le riparazioni, ecc<br />
*il consumo di carburante<br />
*i conducenti autorizzati ad utilizzare il veicolo, con le loro patenti di guida<br />
*gli interventi di manutenzione registrati presso il garage<br />
*metodi o procedure da seguire per la verifica e la manutenzione di routine<br />
*metodi da seguire per le riparazioni non di routine, ecc<br />
*informazioni di fatturazione per il cliente<br />
<br />
== Esempi di programmazione ==<br />
<br />
Basta con questa introduzione, fatta di esempi del mondo reale! Dobbiamo procedere con l'obiettivo principale: la programmazione FreePascal<br />
<br />
<br />
<br />
Dobbiamo considerare la creazione di un semplice modulo con pochi controlli per una applicazione in FreePascal / Lazzaro.<br />
<br />
<div class="floatleft">[[Image:ObjectInspector-TForm.png]]</div><br />
<div class="floatright">[[Image:BlankForm.png]]</div><br />
<br />
<br />
Richiamando la IDE di Lazarus, al programmatore viene presentato un modello vuoto "Form" in progettazione, in cui egli dovrà porre oggetti e vari controlli.<br />
<br />
Si noti che il Form vuoto precostituito è già un oggetto, con le proprie caratteristiche, come la posizione (in alto e sinistra), le dimensioni (altezza e larghezza), il colore, il font di default per l'aggiunta di testo ecc<br />
<br />
<br />
<br />
----<br />
<br />
<br />
Se un controllo Button, un tasto, viene immesso sul Form (tipo TButton), questi avrà una serie di proprietà, che possono essere esaminate nella finestra Object Inspector .<br />
<br />
<br />
Molte delle proprietà hanno nomi simili a quelle del Modulo 'Form', questo è dovuto al fatto che molte proprietà sono'' 'ereditate''' da parte di alcuni comuni antenati di classe, che definiscono le proprietà come sono definite e gestite dalle classi discendenti. <br />
<br />
Così come per le proprietà, l'Object Inspector offre una scheda denominata'' 'Eventi''', che dà accesso ai gestori di eventi 'Event Handlers' che sono metodi per gestire tali eventi, come un clic del mouse su un pulsante (OnClick) o alcuni cambiamento di posizione, le dimensioni o altre proprietà (OnChange).<br />
<br />
L'immagine fisica del pulsante nel Modulo o Form, insieme con tutte le sue proprietà e metodi di gestione, dovrebbe essere considerato come una singola entità o'' 'oggetto''' in Pascal.<br />
<br />
<div class="floatleft">[[Image:ObjectInspector-TButton.png]]</div><br />
<div class="floatright">[[Image:FormWithButton.png]]</div><br />
<div class="floatright">[[Image:Source_FormWithButton1.png ]]</div><br />
<br />
== Object-Oriented Extensions to standard Pascal ==<br />
<br />
La struttura Pascal di tipo record viene estesa per definire un<br />
=== Object ===<br />
<br />
Un oggetto è uno speciale tipo di record. Il record contiene tutti i campi che sono dichiarati nella definizione dell'oggetto (proprio come un convenzionale record), ma ora le procedure e le funzioni possono essere dichiarate come se fossero parte del record e si richiamano come puntatori ai metodi associati con il tipo di oggetto.<br />
<br />
Ad esempio, un oggetto può contenere una serie di valori reali, una matrice,unitamente con un metodo di calcolo della media.<br />
<br />
Type<br />
Average = Object<br />
NumVal: Integer;<br />
Values: Array [1..200] of Real;<br />
Function Mean: Real; { calculates the average value of the array }<br />
End;<br />
<br />
Gli oggetti possono "ereditare" campi e metodi da oggetti "madre". Ciò significa che questi campi e metodi possono essere usati come se fossero incluse negli oggetti dichiarati come un oggetto figlio.<br />
<br />
Inoltre, viene introdotto un concetto di visibilità : i campi, le procedure e le funzioni possono essere dichiarati come pubblici, protetti o privati. Per impostazione predefinita, i campi e metodi sono pubblici, e possono essere esportati al di fuori delle attuali unit. Campi o metodi protetti sono disponibili solo per gli oggetti discendenti dal corrente oggetto antenato. Campi e metodi dichiarati privati sono unicamente accessibili nella unit corrente:<br />
il loro scopo è limitato all'implementazione della corrente unit.<br />
<br />
=== Class ===<br />
Gli oggetti molto spesso non sono usati da se stessi in FreePascal and Lazarus; invece le classi sono largamente usate.<br />
La Classe è definita quasi alla stessa stregua di un oggetto, ma è un puntatore ad un oggetto piuttosto che l'oggetto stesso.<br />
<br />
Tecnicamente, questo significa che la classe è assegnata "on the Heap of a program", mentre l'oggetto viene assegnato in Stack.<br />
Ecco un semplice esempio di dichiarazione di una classe:<br />
<br />
{-----------------------------------------}<br />
{example of Class declaration from the LCL}<br />
{-----------------------------------------}<br />
TPen = class(TFPCustomPen)<br />
private<br />
FColor: TColor;<br />
FPenHandleCached: boolean;<br />
FReference: TWSPenReference;<br />
procedure FreeReference;<br />
function GetHandle: HPEN;<br />
function GetReference: TWSPenReference;<br />
procedure ReferenceNeeded;<br />
procedure SetHandle(const Value: HPEN);<br />
protected<br />
procedure DoAllocateResources; override;<br />
procedure DoDeAllocateResources; override;<br />
procedure DoCopyProps(From: TFPCanvasHelper); override;<br />
procedure SetColor<br />
(const NewColor: TColor; const NewFPColor: TFPColor); virtual;<br />
procedure SetFPColor(const AValue: TFPColor); override;<br />
procedure SetColor(Value: TColor);<br />
procedure SetMode(Value: TPenMode); override;<br />
procedure SetStyle(Value: TPenStyle); override;<br />
procedure SetWidth(value: Integer); override;<br />
public<br />
constructor Create; override;<br />
destructor Destroy; override;<br />
procedure Assign(Source: TPersistent); override;<br />
property Handle: HPEN read GetHandle write SetHandle; deprecated;<br />
property Reference: TWSPenReference read GetReference;<br />
published<br />
property Color: TColor read FColor write SetColor default clBlack;<br />
property Mode default pmCopy;<br />
property Style default psSolid;<br />
property Width default 1;<br />
end;<br />
<br />
<br />
Si noti che questa classe è definita come un istanza di un altra classe '''madre''' o '''antenato''' (''''TFPCustomPen) da cui '''eredita''' tutte le sue proprietà e metodi.Ha alcuni campi propri, raggruppati sotto <br />
*'''private''' - questo significa che gli elementi qui definiti, sono disponibili o visibili da altre classi procedure o funzioni definite all'interno della stessa unit di programma (questo esempio è da'' Graphics'', così che una qualsiasi delle altre classi, come ''TBitMap'',''TPicture'' etc nella stessa unità è in grado di farne uso).<br />
<br />
Esse sono generalmente variabili locali (eg ''FColor'', ''FPenHandleCached'') o metodi usati localmente(''GetHandle'', ''SetHandle'') ma possono essere usate o possono riferirvi voci dichiarate in sezioni '''protected''' or '''public'''.<br />
*'''protected''' - questo significa che le voci definite qui sono solo disponibili o visibili da classi che discendono da quella classe '''antenata''',ed eredita le sue proprietà o metodi<br />
*'''public''' - questo significa che le voci definite qui sono solo disponibili per qualunque unit che includa la unit corrente in essa con la clausula [[Glossary#Uses | Uses]] <br />
*'''published''' - is the same as a '''public''' section, but the compiler also generates type information that is needed for automatic streaming of these classes. Often the list of published items appear in the Object Inspector of Lazarus; if there is no '''published''' list, all the '''public''' fields usually appear in the Object Inspector.<br />
<br />
=== Methods ===<br />
A method is just like a standard procedure or function, but can have some additional '''directives'''.<br />
<br />
Some of the methods defined above are labelled with the directive '''virtual'''; others are labelled with the '''override''' directive.<br />
*'''virtual''' means that the type or actual instance of a method is not known at compile-time, but is selected at run-time depending on what sub-program actually calls the method. It could be considered a place-holder in the definition of the class.<br />
*'''override''' means that at run-time the locally given definition can take the place of a definition inherited from an ancestor class, particularly if it was '''virtual'''. If you particularly want to use the method defined in the ancestor class, it is sometimes necessary to call it specifically with the '''inherited''' clause.<br />
<br />
Methods with no virtual or override directive are '''static''' methods (the usual kind in Pascal). Those with a virtual or override directive are '''dynamic'''.<br />
<br />
Special instances of methods are:<br />
*'''create''' - a '''constructor''' for a class, which takes care of allocating memory, collecting together all the information needed and configuring/initializing the various properties.<br />
*'''destroy''' - a '''destructor''' for a class, which removes all the parts of the class from the system in an orderly and logical way, and returns all its resources for the system to re-use.<br />
<br />
=== Properties ===<br />
<br />
Properties are just like ordinary fields in a conventional Pascal record, but they can have '''read''' and/or '''write''' specifiers.<br />
*'''read''' specifier is a field, or a function that returns a result of the correct type for the property. In the example above, the property ''Color'' has a read specifier ''FColor'', which is a local variable containing the value to be used. If a property has a '''read''' but no '''write''' specifier, it is read-only.<br />
*'''write''' specifier is a field, or a procedure that will store the value of the property in a specific location. In the example above, ''Color'' has a write specifier ''SetColor'' that is a procedure (defined in the '''protected''' section) for writing the color value to some specified location. If a property has a '''write''' but no '''read''' specifier, it is write-only.<br />
*'''default''' - note that it is possible to set a '''default''' value for a property. For example, ''Color'' here is given the default value ''clBlack'', or black, at the time of creation. It could subsequently be given a different value, by a programming assignment statement, or in the Object Inspector.<br />
<br />
== Further information ==<br />
<br />
This has only scratched the surface of the topic. For more details, readers are strongly recommended to read the [http://lazarus-ccr.sourceforge.net/fpcdoc/ref/ref.html FreePascal] manuals, especially Chapters 5 ('''Objects''') and 6 ('''Classes''')<br />
<br />
--[[User:Kirkpatc|Kirkpatc]] 11:04, 20 July 2008 (CEST)<br />
<br />
----<br />
[[Console Mode Pascal]]</div>Amedeohttps://wiki.freepascal.org/index.php?title=Object_Oriented_Programming_with_Free_Pascal_and_Lazarus/it&diff=34775Object Oriented Programming with Free Pascal and Lazarus/it2009-04-01T10:36:57Z<p>Amedeo: /* Class */</p>
<hr />
<div>{{Object_Oriented_Programming_with_FreePascal_and_Lazarus}}<br />
<br />
Esistono molte guide eccellenti su Pascal, ma questa guida tenta di coinvolgere ulteriormente il principiante , nella programmazione orientata agli oggetti o [[Glossary#OO | Object-Oriented Programming]], che è un'estensione dello standard pascal, offerta da Turbo pascal, Delphi e FreePascal/Lazarus.<br />
<br />
Un [[Glossary#Object | Object]] è un'estensione della struttura standard pascal detta [http://wiki.lazarus.freepascal.org/Record record]<br />
<br />
La programmazione Pascal in testo standard è adatta alla creazione di applicazioni che, come le applicazioni Unix tradizionali,sono adatte per fare una cosa e per farla molto bene.<br />
<br />
Ciò che un programma fa può essere un'azione veramente complicata ,e può offrire all'utente molte opzioni di menu,<br />
ma è essenzialmente ristretta ad obbedire a comandi che l'utente digita da tastiera e a listare le sue risposte sul terminale o sulla stampante. <br />
<br />
Per poter produrre una [[Glossary#GUI | Graphical User Interface (GUI)]] usualmente si utilizza una sorta di Metodo di programmazione orientata agli oggetti (spesso facendo uso di [[Glossary#C Programming Language | C]] o di una delle sue varianti, o Visual Basic, o una delle [[Glossary#OO | OO]] varianti di Pascal quali [[Glossary#FreePascal | FreePascal]] con o senza [[Glossary#Lazarus | Lazarus]]). <br />
<br />
In una GUI all'utente vengono presentate schermate con un gran numero di immagini organizzate in modo strutturato, consistenti in un'insieme di strumenti o [[Glossary#Widget | Widgets]] che sono associati con varie azioni quali <br />
*selezioni da menu, <br />
*aperture o salvataggio files , <br />
*connessioni ad Internet, <br />
*esecuzioni di calcoli numerici, etc. <br />
<br />
L'utente dovrà muovere il mouse o qualche altro puntatore o strumento sullo schermo, per selezionare le azioni che saranno eseguite in risposta al click del mouse o ai tasti premuti.<br />
<br />
I sistemi per offrire una complessa interfaccia grafica possono essere scritti in Pascal standard o quasi qualsiasi altro linguaggio di programmazione, ma è molto più facile l'utilizzo di un sistema orientato agli oggetti, in cui ogni oggetto grafico sullo schermo può avere tutte le sue proprietà e le sue procedure e funzioni connesse con il suo uso conglobate in una struttura comune.<br />
<br />
<br />
== Oggetti - una analogia con il mondo reale == <br />
Consideriamo le analogie di un campione di sangue prelevato in un ospedale o in uno studio medico.<br />
=== Campione di sangue ===<br />
Il campione fisico è certamente un oggetto o '''object'''; ed ha , associato con esso una quantità di informazioni,documenti ed altri oggetti fisici. <br />
<br />
*'''Provetta''', del tipo determinato dal test che si dovrà eseguire.<br />
<br />
*'''Metodica''' (o ''metodo'', ''procedura operativa standard'') utilizzata dall'infermiera o dal tecnico di laboratorio che prelevano e processano il campione <br />
** che tipo di provetta si dovrà usare, <br />
**come processare il campione<br />
**come conservarlo prima di consegnarlo al laboratorio. <br />
<br />
*'''Etichetta''' sulla provetta con i dettagli per <br />
**identificare il campione <br />
**Nome e cognome e data di nascita del paziente <br />
** data e ora del prelievo <br />
** analisi richieste. <br />
<br />
*'''Modulo di richiesta''' che accompagna il campione per il laboratorio cui il campione è diretto <br />
** ID Campione<br />
**ID del medico richiedente<br />
** quali analisi il medico richiede e <br />
**anamnesi e dettagli completi del paziente<br />
**La possibile diagnosi di cui si richiede conferma. <br />
<br />
<br />
Una copia delle richiesta viene conservata nella cartella clinica per ricordare al medico di attendersi risultati entro un periodo di tempo adeguato. <br />
<br />
<br />
*In laboratorio - '''metodi locali''' per determinare <br />
**come il campione deve essere analizzato, <br />
**Quale strumento usare, <br />
**come lo strumento dovrà operare e come dovrà essere calibrato, <br />
**come il risultato dovrà essere memorizzato formattato e <br />
**presentato al medico. <br />
<br />
L'effettivo'' 'risultato''' è un dato che il medico usa per formulare la diagnosi, e una copia dei risultati è archiviata nella cartella clinica del paziente.<br />
<br />
Il campione fisico può essere conservato per riferimento,per test di conferma o ulteriori test, o potrà essere smaltito in ottemperanza alle norme per lo smaltimento dei campioni biologici o mediante incenerimento, ci sarà un metodo per descrivere questo procedimento.<br />
<br />
<br />
Non è necessario che il medico dica tutti i dettagli operativi e le istruzioni di lavoro ogni qualvolta che un campione viene prelevato; anzi,egli può avere ben poche conoscenze di come il campione verrà processato dal laboratorio. <br />
<br />
I dettagli dei vari processi sono'' '''ereditati''' dai precedenti processi dei campione in analisi ,ossia a priori si è stabilito il metodo di processo del campione - ci sarà un piano generico per l'intera sequenza, e insieme abbiamo potuto pensare al campione di sangue,a tutti i suoi documenti e dati, e la metodica di base, come a un complesso'' 'oggetto'''.<br />
<br />
<br />
<br />
Nella mente del medico, il campione di sangue è visto come un'unica entità, come i suoi risultati, e per gli infermieri e tecnici il campione, la provetta, l'etichetta e le condizioni di conservazione anch'esse sono identificate come se fossero una sola entità.<br />
<br />
Traduzione da completare.....<br />
<br />
=== Un'altro esempio- Automobile ===<br />
Se non vi piace l'esempio del campione di sangue,lo stesso tipo di ragionamento può essere applicato all'automobile consegnata al garage per una riparazione.<br />
Ciò potrebbe consistere in<br />
*Il veicolo fisico<br />
*i documenti in possesso del proprietario: Libretto di circolazione (comprese targhe), le assicurazioni, le ricevute per l'acquisto, i pezzi di ricambio, le riparazioni, ecc<br />
*il consumo di carburante<br />
*i conducenti autorizzati ad utilizzare il veicolo, con le loro patenti di guida<br />
*gli interventi di manutenzione registrati presso il garage<br />
*metodi o procedure da seguire per la verifica e la manutenzione di routine<br />
*metodi da seguire per le riparazioni non di routine, ecc<br />
*informazioni di fatturazione per il cliente<br />
<br />
== Esempi di programmazione ==<br />
<br />
Basta con questa introduzione, fatta di esempi del mondo reale! Dobbiamo procedere con l'obiettivo principale: la programmazione FreePascal<br />
<br />
<br />
<br />
Dobbiamo considerare la creazione di un semplice modulo con pochi controlli per una applicazione in FreePascal / Lazzaro.<br />
<br />
<div class="floatleft">[[Image:ObjectInspector-TForm.png]]</div><br />
<div class="floatright">[[Image:BlankForm.png]]</div><br />
<br />
<br />
Richiamando la IDE di Lazarus, al programmatore viene presentato un modello vuoto "Form" in progettazione, in cui egli dovrà porre oggetti e vari controlli.<br />
<br />
Si noti che il Form vuoto precostituito è già un oggetto, con le proprie caratteristiche, come la posizione (in alto e sinistra), le dimensioni (altezza e larghezza), il colore, il font di default per l'aggiunta di testo ecc<br />
<br />
<br />
<br />
----<br />
<br />
<br />
Se un controllo Button, un tasto, viene immesso sul Form (tipo TButton), questi avrà una serie di proprietà, che possono essere esaminate nella finestra Object Inspector .<br />
<br />
<br />
Molte delle proprietà hanno nomi simili a quelle del Modulo 'Form', questo è dovuto al fatto che molte proprietà sono'' 'ereditate''' da parte di alcuni comuni antenati di classe, che definiscono le proprietà come sono definite e gestite dalle classi discendenti. <br />
<br />
Così come per le proprietà, l'Object Inspector offre una scheda denominata'' 'Eventi''', che dà accesso ai gestori di eventi 'Event Handlers' che sono metodi per gestire tali eventi, come un clic del mouse su un pulsante (OnClick) o alcuni cambiamento di posizione, le dimensioni o altre proprietà (OnChange).<br />
<br />
L'immagine fisica del pulsante nel Modulo o Form, insieme con tutte le sue proprietà e metodi di gestione, dovrebbe essere considerato come una singola entità o'' 'oggetto''' in Pascal.<br />
<br />
<div class="floatleft">[[Image:ObjectInspector-TButton.png]]</div><br />
<div class="floatright">[[Image:FormWithButton.png]]</div><br />
<div class="floatright">[[Image:Source_FormWithButton1.png ]]</div><br />
<br />
== Object-Oriented Extensions to standard Pascal ==<br />
<br />
La struttura Pascal di tipo record viene estesa per definire un<br />
=== Object ===<br />
<br />
Un oggetto è uno speciale tipo di record. Il record contiene tutti i campi che sono dichiarati nella definizione dell'oggetto (proprio come un convenzionale record), ma ora le procedure e le funzioni possono essere dichiarate come se fossero parte del record e si richiamano come puntatori ai metodi associati con il tipo di oggetto.<br />
<br />
Ad esempio, un oggetto può contenere una serie di valori reali, una matrice,unitamente con un metodo di calcolo della media.<br />
<br />
Type<br />
Average = Object<br />
NumVal: Integer;<br />
Values: Array [1..200] of Real;<br />
Function Mean: Real; { calculates the average value of the array }<br />
End;<br />
<br />
Gli oggetti possono "ereditare" campi e metodi da oggetti "madre". Ciò significa che questi campi e metodi possono essere usati come se fossero incluse negli oggetti dichiarati come un oggetto figlio.<br />
<br />
Inoltre, viene introdotto un concetto di visibilità : i campi, le procedure e le funzioni possono essere dichiarati come pubblici, protetti o privati. Per impostazione predefinita, i campi e metodi sono pubblici, e possono essere esportati al di fuori delle attuali unit. Campi o metodi protetti sono disponibili solo per gli oggetti discendenti dal corrente oggetto antenato. Campi e metodi dichiarati privati sono unicamente accessibili nella unit corrente:<br />
il loro scopo è limitato all'implementazione della corrente unit.<br />
<br />
=== Class ===<br />
Gli oggetti molto spesso non sono usati da se stessi in FreePascal and Lazarus; invece le classi sono largamente usate.<br />
La Classe è definita quasi alla stessa stregua di un oggetto, ma è un puntatore ad un oggetto piuttosto che l'oggetto stesso.<br />
<br />
Tecnicamente, questo significa che la classe è assegnata "on the Heap of a program", mentre l'oggetto viene assegnato in Stack.<br />
Ecco un semplice esempio di dichiarazione di una classe:<br />
<br />
{-----------------------------------------}<br />
{example of Class declaration from the LCL}<br />
{-----------------------------------------}<br />
TPen = class(TFPCustomPen)<br />
private<br />
FColor: TColor;<br />
FPenHandleCached: boolean;<br />
FReference: TWSPenReference;<br />
procedure FreeReference;<br />
function GetHandle: HPEN;<br />
function GetReference: TWSPenReference;<br />
procedure ReferenceNeeded;<br />
procedure SetHandle(const Value: HPEN);<br />
protected<br />
procedure DoAllocateResources; override;<br />
procedure DoDeAllocateResources; override;<br />
procedure DoCopyProps(From: TFPCanvasHelper); override;<br />
procedure SetColor<br />
(const NewColor: TColor; const NewFPColor: TFPColor); virtual;<br />
procedure SetFPColor(const AValue: TFPColor); override;<br />
procedure SetColor(Value: TColor);<br />
procedure SetMode(Value: TPenMode); override;<br />
procedure SetStyle(Value: TPenStyle); override;<br />
procedure SetWidth(value: Integer); override;<br />
public<br />
constructor Create; override;<br />
destructor Destroy; override;<br />
procedure Assign(Source: TPersistent); override;<br />
property Handle: HPEN read GetHandle write SetHandle; deprecated;<br />
property Reference: TWSPenReference read GetReference;<br />
published<br />
property Color: TColor read FColor write SetColor default clBlack;<br />
property Mode default pmCopy;<br />
property Style default psSolid;<br />
property Width default 1;<br />
end;<br />
<br />
<br />
Si noti che questa classe è definita come un istanza di un altra classe '''madre''' o '''antenato''' (''''TFPCustomPen) da cui '''eredita''' tutte le sue proprietà e metodi.Ha alcuni campi propri, raggruppati sotto <br />
*'''private''' - questo significa che gli elementi qui definiti, sono disponibili o visibili da altre classi procedure o funzioni definite all'interno della stessa unit di programma (questo esempio è da'' Graphics'', così che una qualsiasi delle altre classi, come ''TBitMap'',''TPicture'' etc nella stessa unità è in grado di farne uso).<br />
<br />
Esse sono generalmente variabili locali (eg ''FColor'', ''FPenHandleCached'') o metodi usati localmente(''GetHandle'', ''SetHandle'') ma possono essere usate o possono riferirvi voci dichierate in sezioni '''protected''' or '''public'''.<br />
*'''protected''' - this means that items defined here are only available or visible to classes that are descended from this '''ancestor''' class, and inherit its properties or methods<br />
*'''public''' - this means that items defined here are available to any programming unit that includes the current unit in its [[Glossary#Uses | Uses]] clause <br />
*'''published''' - is the same as a '''public''' section, but the compiler also generates type information that is needed for automatic streaming of these classes. Often the list of published items appear in the Object Inspector of Lazarus; if there is no '''published''' list, all the '''public''' fields usually appear in the Object Inspector.<br />
<br />
=== Methods ===<br />
A method is just like a standard procedure or function, but can have some additional '''directives'''.<br />
<br />
Some of the methods defined above are labelled with the directive '''virtual'''; others are labelled with the '''override''' directive.<br />
*'''virtual''' means that the type or actual instance of a method is not known at compile-time, but is selected at run-time depending on what sub-program actually calls the method. It could be considered a place-holder in the definition of the class.<br />
*'''override''' means that at run-time the locally given definition can take the place of a definition inherited from an ancestor class, particularly if it was '''virtual'''. If you particularly want to use the method defined in the ancestor class, it is sometimes necessary to call it specifically with the '''inherited''' clause.<br />
<br />
Methods with no virtual or override directive are '''static''' methods (the usual kind in Pascal). Those with a virtual or override directive are '''dynamic'''.<br />
<br />
Special instances of methods are:<br />
*'''create''' - a '''constructor''' for a class, which takes care of allocating memory, collecting together all the information needed and configuring/initializing the various properties.<br />
*'''destroy''' - a '''destructor''' for a class, which removes all the parts of the class from the system in an orderly and logical way, and returns all its resources for the system to re-use.<br />
<br />
=== Properties ===<br />
<br />
Properties are just like ordinary fields in a conventional Pascal record, but they can have '''read''' and/or '''write''' specifiers.<br />
*'''read''' specifier is a field, or a function that returns a result of the correct type for the property. In the example above, the property ''Color'' has a read specifier ''FColor'', which is a local variable containing the value to be used. If a property has a '''read''' but no '''write''' specifier, it is read-only.<br />
*'''write''' specifier is a field, or a procedure that will store the value of the property in a specific location. In the example above, ''Color'' has a write specifier ''SetColor'' that is a procedure (defined in the '''protected''' section) for writing the color value to some specified location. If a property has a '''write''' but no '''read''' specifier, it is write-only.<br />
*'''default''' - note that it is possible to set a '''default''' value for a property. For example, ''Color'' here is given the default value ''clBlack'', or black, at the time of creation. It could subsequently be given a different value, by a programming assignment statement, or in the Object Inspector.<br />
<br />
== Further information ==<br />
<br />
This has only scratched the surface of the topic. For more details, readers are strongly recommended to read the [http://lazarus-ccr.sourceforge.net/fpcdoc/ref/ref.html FreePascal] manuals, especially Chapters 5 ('''Objects''') and 6 ('''Classes''')<br />
<br />
--[[User:Kirkpatc|Kirkpatc]] 11:04, 20 July 2008 (CEST)<br />
<br />
----<br />
[[Console Mode Pascal]]</div>Amedeohttps://wiki.freepascal.org/index.php?title=Object_Oriented_Programming_with_Free_Pascal_and_Lazarus/it&diff=34774Object Oriented Programming with Free Pascal and Lazarus/it2009-04-01T10:31:50Z<p>Amedeo: /* Class */</p>
<hr />
<div>{{Object_Oriented_Programming_with_FreePascal_and_Lazarus}}<br />
<br />
Esistono molte guide eccellenti su Pascal, ma questa guida tenta di coinvolgere ulteriormente il principiante , nella programmazione orientata agli oggetti o [[Glossary#OO | Object-Oriented Programming]], che è un'estensione dello standard pascal, offerta da Turbo pascal, Delphi e FreePascal/Lazarus.<br />
<br />
Un [[Glossary#Object | Object]] è un'estensione della struttura standard pascal detta [http://wiki.lazarus.freepascal.org/Record record]<br />
<br />
La programmazione Pascal in testo standard è adatta alla creazione di applicazioni che, come le applicazioni Unix tradizionali,sono adatte per fare una cosa e per farla molto bene.<br />
<br />
Ciò che un programma fa può essere un'azione veramente complicata ,e può offrire all'utente molte opzioni di menu,<br />
ma è essenzialmente ristretta ad obbedire a comandi che l'utente digita da tastiera e a listare le sue risposte sul terminale o sulla stampante. <br />
<br />
Per poter produrre una [[Glossary#GUI | Graphical User Interface (GUI)]] usualmente si utilizza una sorta di Metodo di programmazione orientata agli oggetti (spesso facendo uso di [[Glossary#C Programming Language | C]] o di una delle sue varianti, o Visual Basic, o una delle [[Glossary#OO | OO]] varianti di Pascal quali [[Glossary#FreePascal | FreePascal]] con o senza [[Glossary#Lazarus | Lazarus]]). <br />
<br />
In una GUI all'utente vengono presentate schermate con un gran numero di immagini organizzate in modo strutturato, consistenti in un'insieme di strumenti o [[Glossary#Widget | Widgets]] che sono associati con varie azioni quali <br />
*selezioni da menu, <br />
*aperture o salvataggio files , <br />
*connessioni ad Internet, <br />
*esecuzioni di calcoli numerici, etc. <br />
<br />
L'utente dovrà muovere il mouse o qualche altro puntatore o strumento sullo schermo, per selezionare le azioni che saranno eseguite in risposta al click del mouse o ai tasti premuti.<br />
<br />
I sistemi per offrire una complessa interfaccia grafica possono essere scritti in Pascal standard o quasi qualsiasi altro linguaggio di programmazione, ma è molto più facile l'utilizzo di un sistema orientato agli oggetti, in cui ogni oggetto grafico sullo schermo può avere tutte le sue proprietà e le sue procedure e funzioni connesse con il suo uso conglobate in una struttura comune.<br />
<br />
<br />
== Oggetti - una analogia con il mondo reale == <br />
Consideriamo le analogie di un campione di sangue prelevato in un ospedale o in uno studio medico.<br />
=== Campione di sangue ===<br />
Il campione fisico è certamente un oggetto o '''object'''; ed ha , associato con esso una quantità di informazioni,documenti ed altri oggetti fisici. <br />
<br />
*'''Provetta''', del tipo determinato dal test che si dovrà eseguire.<br />
<br />
*'''Metodica''' (o ''metodo'', ''procedura operativa standard'') utilizzata dall'infermiera o dal tecnico di laboratorio che prelevano e processano il campione <br />
** che tipo di provetta si dovrà usare, <br />
**come processare il campione<br />
**come conservarlo prima di consegnarlo al laboratorio. <br />
<br />
*'''Etichetta''' sulla provetta con i dettagli per <br />
**identificare il campione <br />
**Nome e cognome e data di nascita del paziente <br />
** data e ora del prelievo <br />
** analisi richieste. <br />
<br />
*'''Modulo di richiesta''' che accompagna il campione per il laboratorio cui il campione è diretto <br />
** ID Campione<br />
**ID del medico richiedente<br />
** quali analisi il medico richiede e <br />
**anamnesi e dettagli completi del paziente<br />
**La possibile diagnosi di cui si richiede conferma. <br />
<br />
<br />
Una copia delle richiesta viene conservata nella cartella clinica per ricordare al medico di attendersi risultati entro un periodo di tempo adeguato. <br />
<br />
<br />
*In laboratorio - '''metodi locali''' per determinare <br />
**come il campione deve essere analizzato, <br />
**Quale strumento usare, <br />
**come lo strumento dovrà operare e come dovrà essere calibrato, <br />
**come il risultato dovrà essere memorizzato formattato e <br />
**presentato al medico. <br />
<br />
L'effettivo'' 'risultato''' è un dato che il medico usa per formulare la diagnosi, e una copia dei risultati è archiviata nella cartella clinica del paziente.<br />
<br />
Il campione fisico può essere conservato per riferimento,per test di conferma o ulteriori test, o potrà essere smaltito in ottemperanza alle norme per lo smaltimento dei campioni biologici o mediante incenerimento, ci sarà un metodo per descrivere questo procedimento.<br />
<br />
<br />
Non è necessario che il medico dica tutti i dettagli operativi e le istruzioni di lavoro ogni qualvolta che un campione viene prelevato; anzi,egli può avere ben poche conoscenze di come il campione verrà processato dal laboratorio. <br />
<br />
I dettagli dei vari processi sono'' '''ereditati''' dai precedenti processi dei campione in analisi ,ossia a priori si è stabilito il metodo di processo del campione - ci sarà un piano generico per l'intera sequenza, e insieme abbiamo potuto pensare al campione di sangue,a tutti i suoi documenti e dati, e la metodica di base, come a un complesso'' 'oggetto'''.<br />
<br />
<br />
<br />
Nella mente del medico, il campione di sangue è visto come un'unica entità, come i suoi risultati, e per gli infermieri e tecnici il campione, la provetta, l'etichetta e le condizioni di conservazione anch'esse sono identificate come se fossero una sola entità.<br />
<br />
Traduzione da completare.....<br />
<br />
=== Un'altro esempio- Automobile ===<br />
Se non vi piace l'esempio del campione di sangue,lo stesso tipo di ragionamento può essere applicato all'automobile consegnata al garage per una riparazione.<br />
Ciò potrebbe consistere in<br />
*Il veicolo fisico<br />
*i documenti in possesso del proprietario: Libretto di circolazione (comprese targhe), le assicurazioni, le ricevute per l'acquisto, i pezzi di ricambio, le riparazioni, ecc<br />
*il consumo di carburante<br />
*i conducenti autorizzati ad utilizzare il veicolo, con le loro patenti di guida<br />
*gli interventi di manutenzione registrati presso il garage<br />
*metodi o procedure da seguire per la verifica e la manutenzione di routine<br />
*metodi da seguire per le riparazioni non di routine, ecc<br />
*informazioni di fatturazione per il cliente<br />
<br />
== Esempi di programmazione ==<br />
<br />
Basta con questa introduzione, fatta di esempi del mondo reale! Dobbiamo procedere con l'obiettivo principale: la programmazione FreePascal<br />
<br />
<br />
<br />
Dobbiamo considerare la creazione di un semplice modulo con pochi controlli per una applicazione in FreePascal / Lazzaro.<br />
<br />
<div class="floatleft">[[Image:ObjectInspector-TForm.png]]</div><br />
<div class="floatright">[[Image:BlankForm.png]]</div><br />
<br />
<br />
Richiamando la IDE di Lazarus, al programmatore viene presentato un modello vuoto "Form" in progettazione, in cui egli dovrà porre oggetti e vari controlli.<br />
<br />
Si noti che il Form vuoto precostituito è già un oggetto, con le proprie caratteristiche, come la posizione (in alto e sinistra), le dimensioni (altezza e larghezza), il colore, il font di default per l'aggiunta di testo ecc<br />
<br />
<br />
<br />
----<br />
<br />
<br />
Se un controllo Button, un tasto, viene immesso sul Form (tipo TButton), questi avrà una serie di proprietà, che possono essere esaminate nella finestra Object Inspector .<br />
<br />
<br />
Molte delle proprietà hanno nomi simili a quelle del Modulo 'Form', questo è dovuto al fatto che molte proprietà sono'' 'ereditate''' da parte di alcuni comuni antenati di classe, che definiscono le proprietà come sono definite e gestite dalle classi discendenti. <br />
<br />
Così come per le proprietà, l'Object Inspector offre una scheda denominata'' 'Eventi''', che dà accesso ai gestori di eventi 'Event Handlers' che sono metodi per gestire tali eventi, come un clic del mouse su un pulsante (OnClick) o alcuni cambiamento di posizione, le dimensioni o altre proprietà (OnChange).<br />
<br />
L'immagine fisica del pulsante nel Modulo o Form, insieme con tutte le sue proprietà e metodi di gestione, dovrebbe essere considerato come una singola entità o'' 'oggetto''' in Pascal.<br />
<br />
<div class="floatleft">[[Image:ObjectInspector-TButton.png]]</div><br />
<div class="floatright">[[Image:FormWithButton.png]]</div><br />
<div class="floatright">[[Image:Source_FormWithButton1.png ]]</div><br />
<br />
== Object-Oriented Extensions to standard Pascal ==<br />
<br />
La struttura Pascal di tipo record viene estesa per definire un<br />
=== Object ===<br />
<br />
Un oggetto è uno speciale tipo di record. Il record contiene tutti i campi che sono dichiarati nella definizione dell'oggetto (proprio come un convenzionale record), ma ora le procedure e le funzioni possono essere dichiarate come se fossero parte del record e si richiamano come puntatori ai metodi associati con il tipo di oggetto.<br />
<br />
Ad esempio, un oggetto può contenere una serie di valori reali, una matrice,unitamente con un metodo di calcolo della media.<br />
<br />
Type<br />
Average = Object<br />
NumVal: Integer;<br />
Values: Array [1..200] of Real;<br />
Function Mean: Real; { calculates the average value of the array }<br />
End;<br />
<br />
Gli oggetti possono "ereditare" campi e metodi da oggetti "madre". Ciò significa che questi campi e metodi possono essere usati come se fossero incluse negli oggetti dichiarati come un oggetto figlio.<br />
<br />
Inoltre, viene introdotto un concetto di visibilità : i campi, le procedure e le funzioni possono essere dichiarati come pubblici, protetti o privati. Per impostazione predefinita, i campi e metodi sono pubblici, e possono essere esportati al di fuori delle attuali unit. Campi o metodi protetti sono disponibili solo per gli oggetti discendenti dal corrente oggetto antenato. Campi e metodi dichiarati privati sono unicamente accessibili nella unit corrente:<br />
il loro scopo è limitato all'implementazione della corrente unit.<br />
<br />
=== Class ===<br />
Gli oggetti molto spesso non sono usati da se stessi in FreePascal and Lazarus; invece le classi sono largamente usate.<br />
La Classe è definita quasi alla stessa stregua di un oggetto, ma è un puntatore ad un oggetto piuttosto che l'oggetto stesso.<br />
<br />
Tecnicamente, questo significa che la classe è assegnata "on the Heap of a program", mentre l'oggetto viene assegnato in Stack.<br />
Ecco un semplice esempio di dichiarazione di una classe:<br />
<br />
{-----------------------------------------}<br />
{example of Class declaration from the LCL}<br />
{-----------------------------------------}<br />
TPen = class(TFPCustomPen)<br />
private<br />
FColor: TColor;<br />
FPenHandleCached: boolean;<br />
FReference: TWSPenReference;<br />
procedure FreeReference;<br />
function GetHandle: HPEN;<br />
function GetReference: TWSPenReference;<br />
procedure ReferenceNeeded;<br />
procedure SetHandle(const Value: HPEN);<br />
protected<br />
procedure DoAllocateResources; override;<br />
procedure DoDeAllocateResources; override;<br />
procedure DoCopyProps(From: TFPCanvasHelper); override;<br />
procedure SetColor<br />
(const NewColor: TColor; const NewFPColor: TFPColor); virtual;<br />
procedure SetFPColor(const AValue: TFPColor); override;<br />
procedure SetColor(Value: TColor);<br />
procedure SetMode(Value: TPenMode); override;<br />
procedure SetStyle(Value: TPenStyle); override;<br />
procedure SetWidth(value: Integer); override;<br />
public<br />
constructor Create; override;<br />
destructor Destroy; override;<br />
procedure Assign(Source: TPersistent); override;<br />
property Handle: HPEN read GetHandle write SetHandle; deprecated;<br />
property Reference: TWSPenReference read GetReference;<br />
published<br />
property Color: TColor read FColor write SetColor default clBlack;<br />
property Mode default pmCopy;<br />
property Style default psSolid;<br />
property Width default 1;<br />
end;<br />
<br />
<br />
Si noti che questa classe è definita come un istanza di un altra classe '''madre''' o '''antenato''' (''''TFPCustomPen) da cui '''eredita''' tutte le sue proprietà e metodi.Ha alcuni campi propri, raggruppati sotto <br />
*'''private''' - questo significa che gli elementi qui definiti, sono disponibili o visibili da altre classi procedure o funzioni definite all'interno della stessa unit di programma (questo esempio è da'' Graphics'', così che una qualsiasi delle altre classi, come ''TBitMap'',''TPicture'' etc nella stessa unità è in grado di farne uso).<br />
<br />
Esse sono generalmente variabili locali (eg ''FColor'', ''FPenHandleCached'') o metodi usati localmente(''GetHandle'', ''SetHandle'') ma possono essere usate '''protected''' or '''public''' sections.<br />
*'''protected''' - this means that items defined here are only available or visible to classes that are descended from this '''ancestor''' class, and inherit its properties or methods<br />
*'''public''' - this means that items defined here are available to any programming unit that includes the current unit in its [[Glossary#Uses | Uses]] clause <br />
*'''published''' - is the same as a '''public''' section, but the compiler also generates type information that is needed for automatic streaming of these classes. Often the list of published items appear in the Object Inspector of Lazarus; if there is no '''published''' list, all the '''public''' fields usually appear in the Object Inspector.<br />
<br />
=== Methods ===<br />
A method is just like a standard procedure or function, but can have some additional '''directives'''.<br />
<br />
Some of the methods defined above are labelled with the directive '''virtual'''; others are labelled with the '''override''' directive.<br />
*'''virtual''' means that the type or actual instance of a method is not known at compile-time, but is selected at run-time depending on what sub-program actually calls the method. It could be considered a place-holder in the definition of the class.<br />
*'''override''' means that at run-time the locally given definition can take the place of a definition inherited from an ancestor class, particularly if it was '''virtual'''. If you particularly want to use the method defined in the ancestor class, it is sometimes necessary to call it specifically with the '''inherited''' clause.<br />
<br />
Methods with no virtual or override directive are '''static''' methods (the usual kind in Pascal). Those with a virtual or override directive are '''dynamic'''.<br />
<br />
Special instances of methods are:<br />
*'''create''' - a '''constructor''' for a class, which takes care of allocating memory, collecting together all the information needed and configuring/initializing the various properties.<br />
*'''destroy''' - a '''destructor''' for a class, which removes all the parts of the class from the system in an orderly and logical way, and returns all its resources for the system to re-use.<br />
<br />
=== Properties ===<br />
<br />
Properties are just like ordinary fields in a conventional Pascal record, but they can have '''read''' and/or '''write''' specifiers.<br />
*'''read''' specifier is a field, or a function that returns a result of the correct type for the property. In the example above, the property ''Color'' has a read specifier ''FColor'', which is a local variable containing the value to be used. If a property has a '''read''' but no '''write''' specifier, it is read-only.<br />
*'''write''' specifier is a field, or a procedure that will store the value of the property in a specific location. In the example above, ''Color'' has a write specifier ''SetColor'' that is a procedure (defined in the '''protected''' section) for writing the color value to some specified location. If a property has a '''write''' but no '''read''' specifier, it is write-only.<br />
*'''default''' - note that it is possible to set a '''default''' value for a property. For example, ''Color'' here is given the default value ''clBlack'', or black, at the time of creation. It could subsequently be given a different value, by a programming assignment statement, or in the Object Inspector.<br />
<br />
== Further information ==<br />
<br />
This has only scratched the surface of the topic. For more details, readers are strongly recommended to read the [http://lazarus-ccr.sourceforge.net/fpcdoc/ref/ref.html FreePascal] manuals, especially Chapters 5 ('''Objects''') and 6 ('''Classes''')<br />
<br />
--[[User:Kirkpatc|Kirkpatc]] 11:04, 20 July 2008 (CEST)<br />
<br />
----<br />
[[Console Mode Pascal]]</div>Amedeohttps://wiki.freepascal.org/index.php?title=Object_Oriented_Programming_with_Free_Pascal_and_Lazarus/it&diff=34773Object Oriented Programming with Free Pascal and Lazarus/it2009-04-01T10:27:10Z<p>Amedeo: /* Class */</p>
<hr />
<div>{{Object_Oriented_Programming_with_FreePascal_and_Lazarus}}<br />
<br />
Esistono molte guide eccellenti su Pascal, ma questa guida tenta di coinvolgere ulteriormente il principiante , nella programmazione orientata agli oggetti o [[Glossary#OO | Object-Oriented Programming]], che è un'estensione dello standard pascal, offerta da Turbo pascal, Delphi e FreePascal/Lazarus.<br />
<br />
Un [[Glossary#Object | Object]] è un'estensione della struttura standard pascal detta [http://wiki.lazarus.freepascal.org/Record record]<br />
<br />
La programmazione Pascal in testo standard è adatta alla creazione di applicazioni che, come le applicazioni Unix tradizionali,sono adatte per fare una cosa e per farla molto bene.<br />
<br />
Ciò che un programma fa può essere un'azione veramente complicata ,e può offrire all'utente molte opzioni di menu,<br />
ma è essenzialmente ristretta ad obbedire a comandi che l'utente digita da tastiera e a listare le sue risposte sul terminale o sulla stampante. <br />
<br />
Per poter produrre una [[Glossary#GUI | Graphical User Interface (GUI)]] usualmente si utilizza una sorta di Metodo di programmazione orientata agli oggetti (spesso facendo uso di [[Glossary#C Programming Language | C]] o di una delle sue varianti, o Visual Basic, o una delle [[Glossary#OO | OO]] varianti di Pascal quali [[Glossary#FreePascal | FreePascal]] con o senza [[Glossary#Lazarus | Lazarus]]). <br />
<br />
In una GUI all'utente vengono presentate schermate con un gran numero di immagini organizzate in modo strutturato, consistenti in un'insieme di strumenti o [[Glossary#Widget | Widgets]] che sono associati con varie azioni quali <br />
*selezioni da menu, <br />
*aperture o salvataggio files , <br />
*connessioni ad Internet, <br />
*esecuzioni di calcoli numerici, etc. <br />
<br />
L'utente dovrà muovere il mouse o qualche altro puntatore o strumento sullo schermo, per selezionare le azioni che saranno eseguite in risposta al click del mouse o ai tasti premuti.<br />
<br />
I sistemi per offrire una complessa interfaccia grafica possono essere scritti in Pascal standard o quasi qualsiasi altro linguaggio di programmazione, ma è molto più facile l'utilizzo di un sistema orientato agli oggetti, in cui ogni oggetto grafico sullo schermo può avere tutte le sue proprietà e le sue procedure e funzioni connesse con il suo uso conglobate in una struttura comune.<br />
<br />
<br />
== Oggetti - una analogia con il mondo reale == <br />
Consideriamo le analogie di un campione di sangue prelevato in un ospedale o in uno studio medico.<br />
=== Campione di sangue ===<br />
Il campione fisico è certamente un oggetto o '''object'''; ed ha , associato con esso una quantità di informazioni,documenti ed altri oggetti fisici. <br />
<br />
*'''Provetta''', del tipo determinato dal test che si dovrà eseguire.<br />
<br />
*'''Metodica''' (o ''metodo'', ''procedura operativa standard'') utilizzata dall'infermiera o dal tecnico di laboratorio che prelevano e processano il campione <br />
** che tipo di provetta si dovrà usare, <br />
**come processare il campione<br />
**come conservarlo prima di consegnarlo al laboratorio. <br />
<br />
*'''Etichetta''' sulla provetta con i dettagli per <br />
**identificare il campione <br />
**Nome e cognome e data di nascita del paziente <br />
** data e ora del prelievo <br />
** analisi richieste. <br />
<br />
*'''Modulo di richiesta''' che accompagna il campione per il laboratorio cui il campione è diretto <br />
** ID Campione<br />
**ID del medico richiedente<br />
** quali analisi il medico richiede e <br />
**anamnesi e dettagli completi del paziente<br />
**La possibile diagnosi di cui si richiede conferma. <br />
<br />
<br />
Una copia delle richiesta viene conservata nella cartella clinica per ricordare al medico di attendersi risultati entro un periodo di tempo adeguato. <br />
<br />
<br />
*In laboratorio - '''metodi locali''' per determinare <br />
**come il campione deve essere analizzato, <br />
**Quale strumento usare, <br />
**come lo strumento dovrà operare e come dovrà essere calibrato, <br />
**come il risultato dovrà essere memorizzato formattato e <br />
**presentato al medico. <br />
<br />
L'effettivo'' 'risultato''' è un dato che il medico usa per formulare la diagnosi, e una copia dei risultati è archiviata nella cartella clinica del paziente.<br />
<br />
Il campione fisico può essere conservato per riferimento,per test di conferma o ulteriori test, o potrà essere smaltito in ottemperanza alle norme per lo smaltimento dei campioni biologici o mediante incenerimento, ci sarà un metodo per descrivere questo procedimento.<br />
<br />
<br />
Non è necessario che il medico dica tutti i dettagli operativi e le istruzioni di lavoro ogni qualvolta che un campione viene prelevato; anzi,egli può avere ben poche conoscenze di come il campione verrà processato dal laboratorio. <br />
<br />
I dettagli dei vari processi sono'' '''ereditati''' dai precedenti processi dei campione in analisi ,ossia a priori si è stabilito il metodo di processo del campione - ci sarà un piano generico per l'intera sequenza, e insieme abbiamo potuto pensare al campione di sangue,a tutti i suoi documenti e dati, e la metodica di base, come a un complesso'' 'oggetto'''.<br />
<br />
<br />
<br />
Nella mente del medico, il campione di sangue è visto come un'unica entità, come i suoi risultati, e per gli infermieri e tecnici il campione, la provetta, l'etichetta e le condizioni di conservazione anch'esse sono identificate come se fossero una sola entità.<br />
<br />
Traduzione da completare.....<br />
<br />
=== Un'altro esempio- Automobile ===<br />
Se non vi piace l'esempio del campione di sangue,lo stesso tipo di ragionamento può essere applicato all'automobile consegnata al garage per una riparazione.<br />
Ciò potrebbe consistere in<br />
*Il veicolo fisico<br />
*i documenti in possesso del proprietario: Libretto di circolazione (comprese targhe), le assicurazioni, le ricevute per l'acquisto, i pezzi di ricambio, le riparazioni, ecc<br />
*il consumo di carburante<br />
*i conducenti autorizzati ad utilizzare il veicolo, con le loro patenti di guida<br />
*gli interventi di manutenzione registrati presso il garage<br />
*metodi o procedure da seguire per la verifica e la manutenzione di routine<br />
*metodi da seguire per le riparazioni non di routine, ecc<br />
*informazioni di fatturazione per il cliente<br />
<br />
== Esempi di programmazione ==<br />
<br />
Basta con questa introduzione, fatta di esempi del mondo reale! Dobbiamo procedere con l'obiettivo principale: la programmazione FreePascal<br />
<br />
<br />
<br />
Dobbiamo considerare la creazione di un semplice modulo con pochi controlli per una applicazione in FreePascal / Lazzaro.<br />
<br />
<div class="floatleft">[[Image:ObjectInspector-TForm.png]]</div><br />
<div class="floatright">[[Image:BlankForm.png]]</div><br />
<br />
<br />
Richiamando la IDE di Lazarus, al programmatore viene presentato un modello vuoto "Form" in progettazione, in cui egli dovrà porre oggetti e vari controlli.<br />
<br />
Si noti che il Form vuoto precostituito è già un oggetto, con le proprie caratteristiche, come la posizione (in alto e sinistra), le dimensioni (altezza e larghezza), il colore, il font di default per l'aggiunta di testo ecc<br />
<br />
<br />
<br />
----<br />
<br />
<br />
Se un controllo Button, un tasto, viene immesso sul Form (tipo TButton), questi avrà una serie di proprietà, che possono essere esaminate nella finestra Object Inspector .<br />
<br />
<br />
Molte delle proprietà hanno nomi simili a quelle del Modulo 'Form', questo è dovuto al fatto che molte proprietà sono'' 'ereditate''' da parte di alcuni comuni antenati di classe, che definiscono le proprietà come sono definite e gestite dalle classi discendenti. <br />
<br />
Così come per le proprietà, l'Object Inspector offre una scheda denominata'' 'Eventi''', che dà accesso ai gestori di eventi 'Event Handlers' che sono metodi per gestire tali eventi, come un clic del mouse su un pulsante (OnClick) o alcuni cambiamento di posizione, le dimensioni o altre proprietà (OnChange).<br />
<br />
L'immagine fisica del pulsante nel Modulo o Form, insieme con tutte le sue proprietà e metodi di gestione, dovrebbe essere considerato come una singola entità o'' 'oggetto''' in Pascal.<br />
<br />
<div class="floatleft">[[Image:ObjectInspector-TButton.png]]</div><br />
<div class="floatright">[[Image:FormWithButton.png]]</div><br />
<div class="floatright">[[Image:Source_FormWithButton1.png ]]</div><br />
<br />
== Object-Oriented Extensions to standard Pascal ==<br />
<br />
La struttura Pascal di tipo record viene estesa per definire un<br />
=== Object ===<br />
<br />
Un oggetto è uno speciale tipo di record. Il record contiene tutti i campi che sono dichiarati nella definizione dell'oggetto (proprio come un convenzionale record), ma ora le procedure e le funzioni possono essere dichiarate come se fossero parte del record e si richiamano come puntatori ai metodi associati con il tipo di oggetto.<br />
<br />
Ad esempio, un oggetto può contenere una serie di valori reali, una matrice,unitamente con un metodo di calcolo della media.<br />
<br />
Type<br />
Average = Object<br />
NumVal: Integer;<br />
Values: Array [1..200] of Real;<br />
Function Mean: Real; { calculates the average value of the array }<br />
End;<br />
<br />
Gli oggetti possono "ereditare" campi e metodi da oggetti "madre". Ciò significa che questi campi e metodi possono essere usati come se fossero incluse negli oggetti dichiarati come un oggetto figlio.<br />
<br />
Inoltre, viene introdotto un concetto di visibilità : i campi, le procedure e le funzioni possono essere dichiarati come pubblici, protetti o privati. Per impostazione predefinita, i campi e metodi sono pubblici, e possono essere esportati al di fuori delle attuali unit. Campi o metodi protetti sono disponibili solo per gli oggetti discendenti dal corrente oggetto antenato. Campi e metodi dichiarati privati sono unicamente accessibili nella unit corrente:<br />
il loro scopo è limitato all'implementazione della corrente unit.<br />
<br />
=== Class ===<br />
Gli oggetti molto spesso non sono usati da se stessi in FreePascal and Lazarus; invece le classi sono largamente usate.<br />
La Classe è definita quasi alla stessa stregua di un oggetto, ma è un puntatore ad un oggetto piuttosto che l'oggetto stesso.<br />
<br />
Tecnicamente, questo significa che la classe è assegnata "on the Heap of a program", mentre l'oggetto viene assegnato in Stack.<br />
Ecco un semplice esempio di dichiarazione di una classe:<br />
<br />
{-----------------------------------------}<br />
{example of Class declaration from the LCL}<br />
{-----------------------------------------}<br />
TPen = class(TFPCustomPen)<br />
private<br />
FColor: TColor;<br />
FPenHandleCached: boolean;<br />
FReference: TWSPenReference;<br />
procedure FreeReference;<br />
function GetHandle: HPEN;<br />
function GetReference: TWSPenReference;<br />
procedure ReferenceNeeded;<br />
procedure SetHandle(const Value: HPEN);<br />
protected<br />
procedure DoAllocateResources; override;<br />
procedure DoDeAllocateResources; override;<br />
procedure DoCopyProps(From: TFPCanvasHelper); override;<br />
procedure SetColor<br />
(const NewColor: TColor; const NewFPColor: TFPColor); virtual;<br />
procedure SetFPColor(const AValue: TFPColor); override;<br />
procedure SetColor(Value: TColor);<br />
procedure SetMode(Value: TPenMode); override;<br />
procedure SetStyle(Value: TPenStyle); override;<br />
procedure SetWidth(value: Integer); override;<br />
public<br />
constructor Create; override;<br />
destructor Destroy; override;<br />
procedure Assign(Source: TPersistent); override;<br />
property Handle: HPEN read GetHandle write SetHandle; deprecated;<br />
property Reference: TWSPenReference read GetReference;<br />
published<br />
property Color: TColor read FColor write SetColor default clBlack;<br />
property Mode default pmCopy;<br />
property Style default psSolid;<br />
property Width default 1;<br />
end;<br />
<br />
<br />
Si noti che questa classe è definita come un istanza di un altra classe '''madre''' o'''antenato''' (''''TFPCustomPen) da cui '''eredita''' tutte le sue proprietà e metodi.Ha alcuni campi propri, raggruppati sotto <br />
*'' 'private''' - questo significa che gli elementi qui definiti, sono disponibili o visibili da altre classi procedure o funzioni definite all'interno della stessa unit di programma (questo esempio è da'' Graphics'', così che una qualsiasi delle altre classi, come ''TBitMap'',''TPicture'' etc nella stessa unità è in grado di farne uso).<br />
<br />
They are essentially local variables (eg ''FColor'', ''FPenHandleCached'') or locally used methods (''GetHandle'', ''SetHandle'') but can be used or referred to in items declared in the '''protected''' or '''public''' sections.<br />
*'''protected''' - this means that items defined here are only available or visible to classes that are descended from this '''ancestor''' class, and inherit its properties or methods<br />
*'''public''' - this means that items defined here are available to any programming unit that includes the current unit in its [[Glossary#Uses | Uses]] clause <br />
*'''published''' - is the same as a '''public''' section, but the compiler also generates type information that is needed for automatic streaming of these classes. Often the list of published items appear in the Object Inspector of Lazarus; if there is no '''published''' list, all the '''public''' fields usually appear in the Object Inspector.<br />
<br />
=== Methods ===<br />
A method is just like a standard procedure or function, but can have some additional '''directives'''.<br />
<br />
Some of the methods defined above are labelled with the directive '''virtual'''; others are labelled with the '''override''' directive.<br />
*'''virtual''' means that the type or actual instance of a method is not known at compile-time, but is selected at run-time depending on what sub-program actually calls the method. It could be considered a place-holder in the definition of the class.<br />
*'''override''' means that at run-time the locally given definition can take the place of a definition inherited from an ancestor class, particularly if it was '''virtual'''. If you particularly want to use the method defined in the ancestor class, it is sometimes necessary to call it specifically with the '''inherited''' clause.<br />
<br />
Methods with no virtual or override directive are '''static''' methods (the usual kind in Pascal). Those with a virtual or override directive are '''dynamic'''.<br />
<br />
Special instances of methods are:<br />
*'''create''' - a '''constructor''' for a class, which takes care of allocating memory, collecting together all the information needed and configuring/initializing the various properties.<br />
*'''destroy''' - a '''destructor''' for a class, which removes all the parts of the class from the system in an orderly and logical way, and returns all its resources for the system to re-use.<br />
<br />
=== Properties ===<br />
<br />
Properties are just like ordinary fields in a conventional Pascal record, but they can have '''read''' and/or '''write''' specifiers.<br />
*'''read''' specifier is a field, or a function that returns a result of the correct type for the property. In the example above, the property ''Color'' has a read specifier ''FColor'', which is a local variable containing the value to be used. If a property has a '''read''' but no '''write''' specifier, it is read-only.<br />
*'''write''' specifier is a field, or a procedure that will store the value of the property in a specific location. In the example above, ''Color'' has a write specifier ''SetColor'' that is a procedure (defined in the '''protected''' section) for writing the color value to some specified location. If a property has a '''write''' but no '''read''' specifier, it is write-only.<br />
*'''default''' - note that it is possible to set a '''default''' value for a property. For example, ''Color'' here is given the default value ''clBlack'', or black, at the time of creation. It could subsequently be given a different value, by a programming assignment statement, or in the Object Inspector.<br />
<br />
== Further information ==<br />
<br />
This has only scratched the surface of the topic. For more details, readers are strongly recommended to read the [http://lazarus-ccr.sourceforge.net/fpcdoc/ref/ref.html FreePascal] manuals, especially Chapters 5 ('''Objects''') and 6 ('''Classes''')<br />
<br />
--[[User:Kirkpatc|Kirkpatc]] 11:04, 20 July 2008 (CEST)<br />
<br />
----<br />
[[Console Mode Pascal]]</div>Amedeohttps://wiki.freepascal.org/index.php?title=Object_Oriented_Programming_with_Free_Pascal_and_Lazarus/it&diff=34772Object Oriented Programming with Free Pascal and Lazarus/it2009-04-01T10:25:26Z<p>Amedeo: /* Class */</p>
<hr />
<div>{{Object_Oriented_Programming_with_FreePascal_and_Lazarus}}<br />
<br />
Esistono molte guide eccellenti su Pascal, ma questa guida tenta di coinvolgere ulteriormente il principiante , nella programmazione orientata agli oggetti o [[Glossary#OO | Object-Oriented Programming]], che è un'estensione dello standard pascal, offerta da Turbo pascal, Delphi e FreePascal/Lazarus.<br />
<br />
Un [[Glossary#Object | Object]] è un'estensione della struttura standard pascal detta [http://wiki.lazarus.freepascal.org/Record record]<br />
<br />
La programmazione Pascal in testo standard è adatta alla creazione di applicazioni che, come le applicazioni Unix tradizionali,sono adatte per fare una cosa e per farla molto bene.<br />
<br />
Ciò che un programma fa può essere un'azione veramente complicata ,e può offrire all'utente molte opzioni di menu,<br />
ma è essenzialmente ristretta ad obbedire a comandi che l'utente digita da tastiera e a listare le sue risposte sul terminale o sulla stampante. <br />
<br />
Per poter produrre una [[Glossary#GUI | Graphical User Interface (GUI)]] usualmente si utilizza una sorta di Metodo di programmazione orientata agli oggetti (spesso facendo uso di [[Glossary#C Programming Language | C]] o di una delle sue varianti, o Visual Basic, o una delle [[Glossary#OO | OO]] varianti di Pascal quali [[Glossary#FreePascal | FreePascal]] con o senza [[Glossary#Lazarus | Lazarus]]). <br />
<br />
In una GUI all'utente vengono presentate schermate con un gran numero di immagini organizzate in modo strutturato, consistenti in un'insieme di strumenti o [[Glossary#Widget | Widgets]] che sono associati con varie azioni quali <br />
*selezioni da menu, <br />
*aperture o salvataggio files , <br />
*connessioni ad Internet, <br />
*esecuzioni di calcoli numerici, etc. <br />
<br />
L'utente dovrà muovere il mouse o qualche altro puntatore o strumento sullo schermo, per selezionare le azioni che saranno eseguite in risposta al click del mouse o ai tasti premuti.<br />
<br />
I sistemi per offrire una complessa interfaccia grafica possono essere scritti in Pascal standard o quasi qualsiasi altro linguaggio di programmazione, ma è molto più facile l'utilizzo di un sistema orientato agli oggetti, in cui ogni oggetto grafico sullo schermo può avere tutte le sue proprietà e le sue procedure e funzioni connesse con il suo uso conglobate in una struttura comune.<br />
<br />
<br />
== Oggetti - una analogia con il mondo reale == <br />
Consideriamo le analogie di un campione di sangue prelevato in un ospedale o in uno studio medico.<br />
=== Campione di sangue ===<br />
Il campione fisico è certamente un oggetto o '''object'''; ed ha , associato con esso una quantità di informazioni,documenti ed altri oggetti fisici. <br />
<br />
*'''Provetta''', del tipo determinato dal test che si dovrà eseguire.<br />
<br />
*'''Metodica''' (o ''metodo'', ''procedura operativa standard'') utilizzata dall'infermiera o dal tecnico di laboratorio che prelevano e processano il campione <br />
** che tipo di provetta si dovrà usare, <br />
**come processare il campione<br />
**come conservarlo prima di consegnarlo al laboratorio. <br />
<br />
*'''Etichetta''' sulla provetta con i dettagli per <br />
**identificare il campione <br />
**Nome e cognome e data di nascita del paziente <br />
** data e ora del prelievo <br />
** analisi richieste. <br />
<br />
*'''Modulo di richiesta''' che accompagna il campione per il laboratorio cui il campione è diretto <br />
** ID Campione<br />
**ID del medico richiedente<br />
** quali analisi il medico richiede e <br />
**anamnesi e dettagli completi del paziente<br />
**La possibile diagnosi di cui si richiede conferma. <br />
<br />
<br />
Una copia delle richiesta viene conservata nella cartella clinica per ricordare al medico di attendersi risultati entro un periodo di tempo adeguato. <br />
<br />
<br />
*In laboratorio - '''metodi locali''' per determinare <br />
**come il campione deve essere analizzato, <br />
**Quale strumento usare, <br />
**come lo strumento dovrà operare e come dovrà essere calibrato, <br />
**come il risultato dovrà essere memorizzato formattato e <br />
**presentato al medico. <br />
<br />
L'effettivo'' 'risultato''' è un dato che il medico usa per formulare la diagnosi, e una copia dei risultati è archiviata nella cartella clinica del paziente.<br />
<br />
Il campione fisico può essere conservato per riferimento,per test di conferma o ulteriori test, o potrà essere smaltito in ottemperanza alle norme per lo smaltimento dei campioni biologici o mediante incenerimento, ci sarà un metodo per descrivere questo procedimento.<br />
<br />
<br />
Non è necessario che il medico dica tutti i dettagli operativi e le istruzioni di lavoro ogni qualvolta che un campione viene prelevato; anzi,egli può avere ben poche conoscenze di come il campione verrà processato dal laboratorio. <br />
<br />
I dettagli dei vari processi sono'' '''ereditati''' dai precedenti processi dei campione in analisi ,ossia a priori si è stabilito il metodo di processo del campione - ci sarà un piano generico per l'intera sequenza, e insieme abbiamo potuto pensare al campione di sangue,a tutti i suoi documenti e dati, e la metodica di base, come a un complesso'' 'oggetto'''.<br />
<br />
<br />
<br />
Nella mente del medico, il campione di sangue è visto come un'unica entità, come i suoi risultati, e per gli infermieri e tecnici il campione, la provetta, l'etichetta e le condizioni di conservazione anch'esse sono identificate come se fossero una sola entità.<br />
<br />
Traduzione da completare.....<br />
<br />
=== Un'altro esempio- Automobile ===<br />
Se non vi piace l'esempio del campione di sangue,lo stesso tipo di ragionamento può essere applicato all'automobile consegnata al garage per una riparazione.<br />
Ciò potrebbe consistere in<br />
*Il veicolo fisico<br />
*i documenti in possesso del proprietario: Libretto di circolazione (comprese targhe), le assicurazioni, le ricevute per l'acquisto, i pezzi di ricambio, le riparazioni, ecc<br />
*il consumo di carburante<br />
*i conducenti autorizzati ad utilizzare il veicolo, con le loro patenti di guida<br />
*gli interventi di manutenzione registrati presso il garage<br />
*metodi o procedure da seguire per la verifica e la manutenzione di routine<br />
*metodi da seguire per le riparazioni non di routine, ecc<br />
*informazioni di fatturazione per il cliente<br />
<br />
== Esempi di programmazione ==<br />
<br />
Basta con questa introduzione, fatta di esempi del mondo reale! Dobbiamo procedere con l'obiettivo principale: la programmazione FreePascal<br />
<br />
<br />
<br />
Dobbiamo considerare la creazione di un semplice modulo con pochi controlli per una applicazione in FreePascal / Lazzaro.<br />
<br />
<div class="floatleft">[[Image:ObjectInspector-TForm.png]]</div><br />
<div class="floatright">[[Image:BlankForm.png]]</div><br />
<br />
<br />
Richiamando la IDE di Lazarus, al programmatore viene presentato un modello vuoto "Form" in progettazione, in cui egli dovrà porre oggetti e vari controlli.<br />
<br />
Si noti che il Form vuoto precostituito è già un oggetto, con le proprie caratteristiche, come la posizione (in alto e sinistra), le dimensioni (altezza e larghezza), il colore, il font di default per l'aggiunta di testo ecc<br />
<br />
<br />
<br />
----<br />
<br />
<br />
Se un controllo Button, un tasto, viene immesso sul Form (tipo TButton), questi avrà una serie di proprietà, che possono essere esaminate nella finestra Object Inspector .<br />
<br />
<br />
Molte delle proprietà hanno nomi simili a quelle del Modulo 'Form', questo è dovuto al fatto che molte proprietà sono'' 'ereditate''' da parte di alcuni comuni antenati di classe, che definiscono le proprietà come sono definite e gestite dalle classi discendenti. <br />
<br />
Così come per le proprietà, l'Object Inspector offre una scheda denominata'' 'Eventi''', che dà accesso ai gestori di eventi 'Event Handlers' che sono metodi per gestire tali eventi, come un clic del mouse su un pulsante (OnClick) o alcuni cambiamento di posizione, le dimensioni o altre proprietà (OnChange).<br />
<br />
L'immagine fisica del pulsante nel Modulo o Form, insieme con tutte le sue proprietà e metodi di gestione, dovrebbe essere considerato come una singola entità o'' 'oggetto''' in Pascal.<br />
<br />
<div class="floatleft">[[Image:ObjectInspector-TButton.png]]</div><br />
<div class="floatright">[[Image:FormWithButton.png]]</div><br />
<div class="floatright">[[Image:Source_FormWithButton1.png ]]</div><br />
<br />
== Object-Oriented Extensions to standard Pascal ==<br />
<br />
La struttura Pascal di tipo record viene estesa per definire un<br />
=== Object ===<br />
<br />
Un oggetto è uno speciale tipo di record. Il record contiene tutti i campi che sono dichiarati nella definizione dell'oggetto (proprio come un convenzionale record), ma ora le procedure e le funzioni possono essere dichiarate come se fossero parte del record e si richiamano come puntatori ai metodi associati con il tipo di oggetto.<br />
<br />
Ad esempio, un oggetto può contenere una serie di valori reali, una matrice,unitamente con un metodo di calcolo della media.<br />
<br />
Type<br />
Average = Object<br />
NumVal: Integer;<br />
Values: Array [1..200] of Real;<br />
Function Mean: Real; { calculates the average value of the array }<br />
End;<br />
<br />
Gli oggetti possono "ereditare" campi e metodi da oggetti "madre". Ciò significa che questi campi e metodi possono essere usati come se fossero incluse negli oggetti dichiarati come un oggetto figlio.<br />
<br />
Inoltre, viene introdotto un concetto di visibilità : i campi, le procedure e le funzioni possono essere dichiarati come pubblici, protetti o privati. Per impostazione predefinita, i campi e metodi sono pubblici, e possono essere esportati al di fuori delle attuali unit. Campi o metodi protetti sono disponibili solo per gli oggetti discendenti dal corrente oggetto antenato. Campi e metodi dichiarati privati sono unicamente accessibili nella unit corrente:<br />
il loro scopo è limitato all'implementazione della corrente unit.<br />
<br />
=== Class ===<br />
Gli oggetti molto spesso non sono usati da se stessi in FreePascal and Lazarus; invece le classi sono largamente usate.<br />
La Classe è definita quasi alla stessa stregua di un oggetto, ma è un puntatore ad un oggetto piuttosto che l'oggetto stesso.<br />
<br />
Tecnicamente, questo significa che la classe è assegnata "on the Heap of a program", mentre l'oggetto viene assegnato in Stack.<br />
Ecco un semplice esempio di dichiarazione di una classe:<br />
<br />
{-----------------------------------------}<br />
{example of Class declaration from the LCL}<br />
{-----------------------------------------}<br />
TPen = class(TFPCustomPen)<br />
private<br />
FColor: TColor;<br />
FPenHandleCached: boolean;<br />
FReference: TWSPenReference;<br />
procedure FreeReference;<br />
function GetHandle: HPEN;<br />
function GetReference: TWSPenReference;<br />
procedure ReferenceNeeded;<br />
procedure SetHandle(const Value: HPEN);<br />
protected<br />
procedure DoAllocateResources; override;<br />
procedure DoDeAllocateResources; override;<br />
procedure DoCopyProps(From: TFPCanvasHelper); override;<br />
procedure SetColor<br />
(const NewColor: TColor; const NewFPColor: TFPColor); virtual;<br />
procedure SetFPColor(const AValue: TFPColor); override;<br />
procedure SetColor(Value: TColor);<br />
procedure SetMode(Value: TPenMode); override;<br />
procedure SetStyle(Value: TPenStyle); override;<br />
procedure SetWidth(value: Integer); override;<br />
public<br />
constructor Create; override;<br />
destructor Destroy; override;<br />
procedure Assign(Source: TPersistent); override;<br />
property Handle: HPEN read GetHandle write SetHandle; deprecated;<br />
property Reference: TWSPenReference read GetReference;<br />
published<br />
property Color: TColor read FColor write SetColor default clBlack;<br />
property Mode default pmCopy;<br />
property Style default psSolid;<br />
property Width default 1;<br />
end;<br />
<br />
<br />
Si noti che questa classe è definita come un istanza di un altra classe '' 'madre''' o'' 'antenato''' (''''TFPCustomPen) da cui '' 'eredita''' tutte le sue proprietà e metodi.Ha alcuni campi propri, raggruppati sotto *'' 'private''' - questo significa che gli elementi qui definiti, sono disponibili o visibili da altre classi procedure o funzioni definite all'interno della stessa unit di programma (questo esempio è da'' Graphics'', così che una qualsiasi delle altre classi, come ''TBitMap'',''TPicture'' etc nella stessa unità è in grado di farne uso).<br />
<br />
They are essentially local variables (eg ''FColor'', ''FPenHandleCached'') or locally used methods (''GetHandle'', ''SetHandle'') but can be used or referred to in items declared in the '''protected''' or '''public''' sections.<br />
*'''protected''' - this means that items defined here are only available or visible to classes that are descended from this '''ancestor''' class, and inherit its properties or methods<br />
*'''public''' - this means that items defined here are available to any programming unit that includes the current unit in its [[Glossary#Uses | Uses]] clause <br />
*'''published''' - is the same as a '''public''' section, but the compiler also generates type information that is needed for automatic streaming of these classes. Often the list of published items appear in the Object Inspector of Lazarus; if there is no '''published''' list, all the '''public''' fields usually appear in the Object Inspector.<br />
<br />
=== Methods ===<br />
A method is just like a standard procedure or function, but can have some additional '''directives'''.<br />
<br />
Some of the methods defined above are labelled with the directive '''virtual'''; others are labelled with the '''override''' directive.<br />
*'''virtual''' means that the type or actual instance of a method is not known at compile-time, but is selected at run-time depending on what sub-program actually calls the method. It could be considered a place-holder in the definition of the class.<br />
*'''override''' means that at run-time the locally given definition can take the place of a definition inherited from an ancestor class, particularly if it was '''virtual'''. If you particularly want to use the method defined in the ancestor class, it is sometimes necessary to call it specifically with the '''inherited''' clause.<br />
<br />
Methods with no virtual or override directive are '''static''' methods (the usual kind in Pascal). Those with a virtual or override directive are '''dynamic'''.<br />
<br />
Special instances of methods are:<br />
*'''create''' - a '''constructor''' for a class, which takes care of allocating memory, collecting together all the information needed and configuring/initializing the various properties.<br />
*'''destroy''' - a '''destructor''' for a class, which removes all the parts of the class from the system in an orderly and logical way, and returns all its resources for the system to re-use.<br />
<br />
=== Properties ===<br />
<br />
Properties are just like ordinary fields in a conventional Pascal record, but they can have '''read''' and/or '''write''' specifiers.<br />
*'''read''' specifier is a field, or a function that returns a result of the correct type for the property. In the example above, the property ''Color'' has a read specifier ''FColor'', which is a local variable containing the value to be used. If a property has a '''read''' but no '''write''' specifier, it is read-only.<br />
*'''write''' specifier is a field, or a procedure that will store the value of the property in a specific location. In the example above, ''Color'' has a write specifier ''SetColor'' that is a procedure (defined in the '''protected''' section) for writing the color value to some specified location. If a property has a '''write''' but no '''read''' specifier, it is write-only.<br />
*'''default''' - note that it is possible to set a '''default''' value for a property. For example, ''Color'' here is given the default value ''clBlack'', or black, at the time of creation. It could subsequently be given a different value, by a programming assignment statement, or in the Object Inspector.<br />
<br />
== Further information ==<br />
<br />
This has only scratched the surface of the topic. For more details, readers are strongly recommended to read the [http://lazarus-ccr.sourceforge.net/fpcdoc/ref/ref.html FreePascal] manuals, especially Chapters 5 ('''Objects''') and 6 ('''Classes''')<br />
<br />
--[[User:Kirkpatc|Kirkpatc]] 11:04, 20 July 2008 (CEST)<br />
<br />
----<br />
[[Console Mode Pascal]]</div>Amedeohttps://wiki.freepascal.org/index.php?title=Object_Oriented_Programming_with_Free_Pascal_and_Lazarus/it&diff=34771Object Oriented Programming with Free Pascal and Lazarus/it2009-04-01T10:04:54Z<p>Amedeo: /* Class */</p>
<hr />
<div>{{Object_Oriented_Programming_with_FreePascal_and_Lazarus}}<br />
<br />
Esistono molte guide eccellenti su Pascal, ma questa guida tenta di coinvolgere ulteriormente il principiante , nella programmazione orientata agli oggetti o [[Glossary#OO | Object-Oriented Programming]], che è un'estensione dello standard pascal, offerta da Turbo pascal, Delphi e FreePascal/Lazarus.<br />
<br />
Un [[Glossary#Object | Object]] è un'estensione della struttura standard pascal detta [http://wiki.lazarus.freepascal.org/Record record]<br />
<br />
La programmazione Pascal in testo standard è adatta alla creazione di applicazioni che, come le applicazioni Unix tradizionali,sono adatte per fare una cosa e per farla molto bene.<br />
<br />
Ciò che un programma fa può essere un'azione veramente complicata ,e può offrire all'utente molte opzioni di menu,<br />
ma è essenzialmente ristretta ad obbedire a comandi che l'utente digita da tastiera e a listare le sue risposte sul terminale o sulla stampante. <br />
<br />
Per poter produrre una [[Glossary#GUI | Graphical User Interface (GUI)]] usualmente si utilizza una sorta di Metodo di programmazione orientata agli oggetti (spesso facendo uso di [[Glossary#C Programming Language | C]] o di una delle sue varianti, o Visual Basic, o una delle [[Glossary#OO | OO]] varianti di Pascal quali [[Glossary#FreePascal | FreePascal]] con o senza [[Glossary#Lazarus | Lazarus]]). <br />
<br />
In una GUI all'utente vengono presentate schermate con un gran numero di immagini organizzate in modo strutturato, consistenti in un'insieme di strumenti o [[Glossary#Widget | Widgets]] che sono associati con varie azioni quali <br />
*selezioni da menu, <br />
*aperture o salvataggio files , <br />
*connessioni ad Internet, <br />
*esecuzioni di calcoli numerici, etc. <br />
<br />
L'utente dovrà muovere il mouse o qualche altro puntatore o strumento sullo schermo, per selezionare le azioni che saranno eseguite in risposta al click del mouse o ai tasti premuti.<br />
<br />
I sistemi per offrire una complessa interfaccia grafica possono essere scritti in Pascal standard o quasi qualsiasi altro linguaggio di programmazione, ma è molto più facile l'utilizzo di un sistema orientato agli oggetti, in cui ogni oggetto grafico sullo schermo può avere tutte le sue proprietà e le sue procedure e funzioni connesse con il suo uso conglobate in una struttura comune.<br />
<br />
<br />
== Oggetti - una analogia con il mondo reale == <br />
Consideriamo le analogie di un campione di sangue prelevato in un ospedale o in uno studio medico.<br />
=== Campione di sangue ===<br />
Il campione fisico è certamente un oggetto o '''object'''; ed ha , associato con esso una quantità di informazioni,documenti ed altri oggetti fisici. <br />
<br />
*'''Provetta''', del tipo determinato dal test che si dovrà eseguire.<br />
<br />
*'''Metodica''' (o ''metodo'', ''procedura operativa standard'') utilizzata dall'infermiera o dal tecnico di laboratorio che prelevano e processano il campione <br />
** che tipo di provetta si dovrà usare, <br />
**come processare il campione<br />
**come conservarlo prima di consegnarlo al laboratorio. <br />
<br />
*'''Etichetta''' sulla provetta con i dettagli per <br />
**identificare il campione <br />
**Nome e cognome e data di nascita del paziente <br />
** data e ora del prelievo <br />
** analisi richieste. <br />
<br />
*'''Modulo di richiesta''' che accompagna il campione per il laboratorio cui il campione è diretto <br />
** ID Campione<br />
**ID del medico richiedente<br />
** quali analisi il medico richiede e <br />
**anamnesi e dettagli completi del paziente<br />
**La possibile diagnosi di cui si richiede conferma. <br />
<br />
<br />
Una copia delle richiesta viene conservata nella cartella clinica per ricordare al medico di attendersi risultati entro un periodo di tempo adeguato. <br />
<br />
<br />
*In laboratorio - '''metodi locali''' per determinare <br />
**come il campione deve essere analizzato, <br />
**Quale strumento usare, <br />
**come lo strumento dovrà operare e come dovrà essere calibrato, <br />
**come il risultato dovrà essere memorizzato formattato e <br />
**presentato al medico. <br />
<br />
L'effettivo'' 'risultato''' è un dato che il medico usa per formulare la diagnosi, e una copia dei risultati è archiviata nella cartella clinica del paziente.<br />
<br />
Il campione fisico può essere conservato per riferimento,per test di conferma o ulteriori test, o potrà essere smaltito in ottemperanza alle norme per lo smaltimento dei campioni biologici o mediante incenerimento, ci sarà un metodo per descrivere questo procedimento.<br />
<br />
<br />
Non è necessario che il medico dica tutti i dettagli operativi e le istruzioni di lavoro ogni qualvolta che un campione viene prelevato; anzi,egli può avere ben poche conoscenze di come il campione verrà processato dal laboratorio. <br />
<br />
I dettagli dei vari processi sono'' '''ereditati''' dai precedenti processi dei campione in analisi ,ossia a priori si è stabilito il metodo di processo del campione - ci sarà un piano generico per l'intera sequenza, e insieme abbiamo potuto pensare al campione di sangue,a tutti i suoi documenti e dati, e la metodica di base, come a un complesso'' 'oggetto'''.<br />
<br />
<br />
<br />
Nella mente del medico, il campione di sangue è visto come un'unica entità, come i suoi risultati, e per gli infermieri e tecnici il campione, la provetta, l'etichetta e le condizioni di conservazione anch'esse sono identificate come se fossero una sola entità.<br />
<br />
Traduzione da completare.....<br />
<br />
=== Un'altro esempio- Automobile ===<br />
Se non vi piace l'esempio del campione di sangue,lo stesso tipo di ragionamento può essere applicato all'automobile consegnata al garage per una riparazione.<br />
Ciò potrebbe consistere in<br />
*Il veicolo fisico<br />
*i documenti in possesso del proprietario: Libretto di circolazione (comprese targhe), le assicurazioni, le ricevute per l'acquisto, i pezzi di ricambio, le riparazioni, ecc<br />
*il consumo di carburante<br />
*i conducenti autorizzati ad utilizzare il veicolo, con le loro patenti di guida<br />
*gli interventi di manutenzione registrati presso il garage<br />
*metodi o procedure da seguire per la verifica e la manutenzione di routine<br />
*metodi da seguire per le riparazioni non di routine, ecc<br />
*informazioni di fatturazione per il cliente<br />
<br />
== Esempi di programmazione ==<br />
<br />
Basta con questa introduzione, fatta di esempi del mondo reale! Dobbiamo procedere con l'obiettivo principale: la programmazione FreePascal<br />
<br />
<br />
<br />
Dobbiamo considerare la creazione di un semplice modulo con pochi controlli per una applicazione in FreePascal / Lazzaro.<br />
<br />
<div class="floatleft">[[Image:ObjectInspector-TForm.png]]</div><br />
<div class="floatright">[[Image:BlankForm.png]]</div><br />
<br />
<br />
Richiamando la IDE di Lazarus, al programmatore viene presentato un modello vuoto "Form" in progettazione, in cui egli dovrà porre oggetti e vari controlli.<br />
<br />
Si noti che il Form vuoto precostituito è già un oggetto, con le proprie caratteristiche, come la posizione (in alto e sinistra), le dimensioni (altezza e larghezza), il colore, il font di default per l'aggiunta di testo ecc<br />
<br />
<br />
<br />
----<br />
<br />
<br />
Se un controllo Button, un tasto, viene immesso sul Form (tipo TButton), questi avrà una serie di proprietà, che possono essere esaminate nella finestra Object Inspector .<br />
<br />
<br />
Molte delle proprietà hanno nomi simili a quelle del Modulo 'Form', questo è dovuto al fatto che molte proprietà sono'' 'ereditate''' da parte di alcuni comuni antenati di classe, che definiscono le proprietà come sono definite e gestite dalle classi discendenti. <br />
<br />
Così come per le proprietà, l'Object Inspector offre una scheda denominata'' 'Eventi''', che dà accesso ai gestori di eventi 'Event Handlers' che sono metodi per gestire tali eventi, come un clic del mouse su un pulsante (OnClick) o alcuni cambiamento di posizione, le dimensioni o altre proprietà (OnChange).<br />
<br />
L'immagine fisica del pulsante nel Modulo o Form, insieme con tutte le sue proprietà e metodi di gestione, dovrebbe essere considerato come una singola entità o'' 'oggetto''' in Pascal.<br />
<br />
<div class="floatleft">[[Image:ObjectInspector-TButton.png]]</div><br />
<div class="floatright">[[Image:FormWithButton.png]]</div><br />
<div class="floatright">[[Image:Source_FormWithButton1.png ]]</div><br />
<br />
== Object-Oriented Extensions to standard Pascal ==<br />
<br />
La struttura Pascal di tipo record viene estesa per definire un<br />
=== Object ===<br />
<br />
Un oggetto è uno speciale tipo di record. Il record contiene tutti i campi che sono dichiarati nella definizione dell'oggetto (proprio come un convenzionale record), ma ora le procedure e le funzioni possono essere dichiarate come se fossero parte del record e si richiamano come puntatori ai metodi associati con il tipo di oggetto.<br />
<br />
Ad esempio, un oggetto può contenere una serie di valori reali, una matrice,unitamente con un metodo di calcolo della media.<br />
<br />
Type<br />
Average = Object<br />
NumVal: Integer;<br />
Values: Array [1..200] of Real;<br />
Function Mean: Real; { calculates the average value of the array }<br />
End;<br />
<br />
Gli oggetti possono "ereditare" campi e metodi da oggetti "madre". Ciò significa che questi campi e metodi possono essere usati come se fossero incluse negli oggetti dichiarati come un oggetto figlio.<br />
<br />
Inoltre, viene introdotto un concetto di visibilità : i campi, le procedure e le funzioni possono essere dichiarati come pubblici, protetti o privati. Per impostazione predefinita, i campi e metodi sono pubblici, e possono essere esportati al di fuori delle attuali unit. Campi o metodi protetti sono disponibili solo per gli oggetti discendenti dal corrente oggetto antenato. Campi e metodi dichiarati privati sono unicamente accessibili nella unit corrente:<br />
il loro scopo è limitato all'implementazione della corrente unit.<br />
<br />
=== Class ===<br />
Gli oggetti molto spesso non sono usati da se stessi in FreePascal and Lazarus; invece le classi sono largamente usate.<br />
La Classe è definita quasi alla stessa stregua di un oggetto, ma è un puntatore ad un oggetto piuttosto che l'oggetto stesso.<br />
<br />
Tecnicamente, questo significa che la classe è assegnata "on the Heap of a program", mentre l'oggetto viene assegnato in Stack.<br />
Ecco un semplice esempio di dichiarazione di una classe:<br />
<br />
{-----------------------------------------}<br />
{example of Class declaration from the LCL}<br />
{-----------------------------------------}<br />
TPen = class(TFPCustomPen)<br />
private<br />
FColor: TColor;<br />
FPenHandleCached: boolean;<br />
FReference: TWSPenReference;<br />
procedure FreeReference;<br />
function GetHandle: HPEN;<br />
function GetReference: TWSPenReference;<br />
procedure ReferenceNeeded;<br />
procedure SetHandle(const Value: HPEN);<br />
protected<br />
procedure DoAllocateResources; override;<br />
procedure DoDeAllocateResources; override;<br />
procedure DoCopyProps(From: TFPCanvasHelper); override;<br />
procedure SetColor<br />
(const NewColor: TColor; const NewFPColor: TFPColor); virtual;<br />
procedure SetFPColor(const AValue: TFPColor); override;<br />
procedure SetColor(Value: TColor);<br />
procedure SetMode(Value: TPenMode); override;<br />
procedure SetStyle(Value: TPenStyle); override;<br />
procedure SetWidth(value: Integer); override;<br />
public<br />
constructor Create; override;<br />
destructor Destroy; override;<br />
procedure Assign(Source: TPersistent); override;<br />
property Handle: HPEN read GetHandle write SetHandle; deprecated;<br />
property Reference: TWSPenReference read GetReference;<br />
published<br />
property Color: TColor read FColor write SetColor default clBlack;<br />
property Mode default pmCopy;<br />
property Style default psSolid;<br />
property Width default 1;<br />
end;<br />
<br />
<br />
Note that this class is defined as an instance of another '''parent''' or '''ancestor''' class (''TFPCustomPen'') from which it '''inherits''' all its properties and methods. It has some fields of its own, grouped under<br />
*'''private''' - this means that items defined here are only available or visible to other classes or procedures/function defined within the same program unit (this example is from ''Graphics'', so any of the other classes such as ''TBitMap'', ''TPicture'' etc in the same unit can use them). They are essentially local variables (eg ''FColor'', ''FPenHandleCached'') or locally used methods (''GetHandle'', ''SetHandle'') but can be used or referred to in items declared in the '''protected''' or '''public''' sections.<br />
*'''protected''' - this means that items defined here are only available or visible to classes that are descended from this '''ancestor''' class, and inherit its properties or methods<br />
*'''public''' - this means that items defined here are available to any programming unit that includes the current unit in its [[Glossary#Uses | Uses]] clause <br />
*'''published''' - is the same as a '''public''' section, but the compiler also generates type information that is needed for automatic streaming of these classes. Often the list of published items appear in the Object Inspector of Lazarus; if there is no '''published''' list, all the '''public''' fields usually appear in the Object Inspector.<br />
<br />
=== Methods ===<br />
A method is just like a standard procedure or function, but can have some additional '''directives'''.<br />
<br />
Some of the methods defined above are labelled with the directive '''virtual'''; others are labelled with the '''override''' directive.<br />
*'''virtual''' means that the type or actual instance of a method is not known at compile-time, but is selected at run-time depending on what sub-program actually calls the method. It could be considered a place-holder in the definition of the class.<br />
*'''override''' means that at run-time the locally given definition can take the place of a definition inherited from an ancestor class, particularly if it was '''virtual'''. If you particularly want to use the method defined in the ancestor class, it is sometimes necessary to call it specifically with the '''inherited''' clause.<br />
<br />
Methods with no virtual or override directive are '''static''' methods (the usual kind in Pascal). Those with a virtual or override directive are '''dynamic'''.<br />
<br />
Special instances of methods are:<br />
*'''create''' - a '''constructor''' for a class, which takes care of allocating memory, collecting together all the information needed and configuring/initializing the various properties.<br />
*'''destroy''' - a '''destructor''' for a class, which removes all the parts of the class from the system in an orderly and logical way, and returns all its resources for the system to re-use.<br />
<br />
=== Properties ===<br />
<br />
Properties are just like ordinary fields in a conventional Pascal record, but they can have '''read''' and/or '''write''' specifiers.<br />
*'''read''' specifier is a field, or a function that returns a result of the correct type for the property. In the example above, the property ''Color'' has a read specifier ''FColor'', which is a local variable containing the value to be used. If a property has a '''read''' but no '''write''' specifier, it is read-only.<br />
*'''write''' specifier is a field, or a procedure that will store the value of the property in a specific location. In the example above, ''Color'' has a write specifier ''SetColor'' that is a procedure (defined in the '''protected''' section) for writing the color value to some specified location. If a property has a '''write''' but no '''read''' specifier, it is write-only.<br />
*'''default''' - note that it is possible to set a '''default''' value for a property. For example, ''Color'' here is given the default value ''clBlack'', or black, at the time of creation. It could subsequently be given a different value, by a programming assignment statement, or in the Object Inspector.<br />
<br />
== Further information ==<br />
<br />
This has only scratched the surface of the topic. For more details, readers are strongly recommended to read the [http://lazarus-ccr.sourceforge.net/fpcdoc/ref/ref.html FreePascal] manuals, especially Chapters 5 ('''Objects''') and 6 ('''Classes''')<br />
<br />
--[[User:Kirkpatc|Kirkpatc]] 11:04, 20 July 2008 (CEST)<br />
<br />
----<br />
[[Console Mode Pascal]]</div>Amedeohttps://wiki.freepascal.org/index.php?title=Object_Oriented_Programming_with_Free_Pascal_and_Lazarus/it&diff=34770Object Oriented Programming with Free Pascal and Lazarus/it2009-04-01T10:03:26Z<p>Amedeo: /* Class */</p>
<hr />
<div>{{Object_Oriented_Programming_with_FreePascal_and_Lazarus}}<br />
<br />
Esistono molte guide eccellenti su Pascal, ma questa guida tenta di coinvolgere ulteriormente il principiante , nella programmazione orientata agli oggetti o [[Glossary#OO | Object-Oriented Programming]], che è un'estensione dello standard pascal, offerta da Turbo pascal, Delphi e FreePascal/Lazarus.<br />
<br />
Un [[Glossary#Object | Object]] è un'estensione della struttura standard pascal detta [http://wiki.lazarus.freepascal.org/Record record]<br />
<br />
La programmazione Pascal in testo standard è adatta alla creazione di applicazioni che, come le applicazioni Unix tradizionali,sono adatte per fare una cosa e per farla molto bene.<br />
<br />
Ciò che un programma fa può essere un'azione veramente complicata ,e può offrire all'utente molte opzioni di menu,<br />
ma è essenzialmente ristretta ad obbedire a comandi che l'utente digita da tastiera e a listare le sue risposte sul terminale o sulla stampante. <br />
<br />
Per poter produrre una [[Glossary#GUI | Graphical User Interface (GUI)]] usualmente si utilizza una sorta di Metodo di programmazione orientata agli oggetti (spesso facendo uso di [[Glossary#C Programming Language | C]] o di una delle sue varianti, o Visual Basic, o una delle [[Glossary#OO | OO]] varianti di Pascal quali [[Glossary#FreePascal | FreePascal]] con o senza [[Glossary#Lazarus | Lazarus]]). <br />
<br />
In una GUI all'utente vengono presentate schermate con un gran numero di immagini organizzate in modo strutturato, consistenti in un'insieme di strumenti o [[Glossary#Widget | Widgets]] che sono associati con varie azioni quali <br />
*selezioni da menu, <br />
*aperture o salvataggio files , <br />
*connessioni ad Internet, <br />
*esecuzioni di calcoli numerici, etc. <br />
<br />
L'utente dovrà muovere il mouse o qualche altro puntatore o strumento sullo schermo, per selezionare le azioni che saranno eseguite in risposta al click del mouse o ai tasti premuti.<br />
<br />
I sistemi per offrire una complessa interfaccia grafica possono essere scritti in Pascal standard o quasi qualsiasi altro linguaggio di programmazione, ma è molto più facile l'utilizzo di un sistema orientato agli oggetti, in cui ogni oggetto grafico sullo schermo può avere tutte le sue proprietà e le sue procedure e funzioni connesse con il suo uso conglobate in una struttura comune.<br />
<br />
<br />
== Oggetti - una analogia con il mondo reale == <br />
Consideriamo le analogie di un campione di sangue prelevato in un ospedale o in uno studio medico.<br />
=== Campione di sangue ===<br />
Il campione fisico è certamente un oggetto o '''object'''; ed ha , associato con esso una quantità di informazioni,documenti ed altri oggetti fisici. <br />
<br />
*'''Provetta''', del tipo determinato dal test che si dovrà eseguire.<br />
<br />
*'''Metodica''' (o ''metodo'', ''procedura operativa standard'') utilizzata dall'infermiera o dal tecnico di laboratorio che prelevano e processano il campione <br />
** che tipo di provetta si dovrà usare, <br />
**come processare il campione<br />
**come conservarlo prima di consegnarlo al laboratorio. <br />
<br />
*'''Etichetta''' sulla provetta con i dettagli per <br />
**identificare il campione <br />
**Nome e cognome e data di nascita del paziente <br />
** data e ora del prelievo <br />
** analisi richieste. <br />
<br />
*'''Modulo di richiesta''' che accompagna il campione per il laboratorio cui il campione è diretto <br />
** ID Campione<br />
**ID del medico richiedente<br />
** quali analisi il medico richiede e <br />
**anamnesi e dettagli completi del paziente<br />
**La possibile diagnosi di cui si richiede conferma. <br />
<br />
<br />
Una copia delle richiesta viene conservata nella cartella clinica per ricordare al medico di attendersi risultati entro un periodo di tempo adeguato. <br />
<br />
<br />
*In laboratorio - '''metodi locali''' per determinare <br />
**come il campione deve essere analizzato, <br />
**Quale strumento usare, <br />
**come lo strumento dovrà operare e come dovrà essere calibrato, <br />
**come il risultato dovrà essere memorizzato formattato e <br />
**presentato al medico. <br />
<br />
L'effettivo'' 'risultato''' è un dato che il medico usa per formulare la diagnosi, e una copia dei risultati è archiviata nella cartella clinica del paziente.<br />
<br />
Il campione fisico può essere conservato per riferimento,per test di conferma o ulteriori test, o potrà essere smaltito in ottemperanza alle norme per lo smaltimento dei campioni biologici o mediante incenerimento, ci sarà un metodo per descrivere questo procedimento.<br />
<br />
<br />
Non è necessario che il medico dica tutti i dettagli operativi e le istruzioni di lavoro ogni qualvolta che un campione viene prelevato; anzi,egli può avere ben poche conoscenze di come il campione verrà processato dal laboratorio. <br />
<br />
I dettagli dei vari processi sono'' '''ereditati''' dai precedenti processi dei campione in analisi ,ossia a priori si è stabilito il metodo di processo del campione - ci sarà un piano generico per l'intera sequenza, e insieme abbiamo potuto pensare al campione di sangue,a tutti i suoi documenti e dati, e la metodica di base, come a un complesso'' 'oggetto'''.<br />
<br />
<br />
<br />
Nella mente del medico, il campione di sangue è visto come un'unica entità, come i suoi risultati, e per gli infermieri e tecnici il campione, la provetta, l'etichetta e le condizioni di conservazione anch'esse sono identificate come se fossero una sola entità.<br />
<br />
Traduzione da completare.....<br />
<br />
=== Un'altro esempio- Automobile ===<br />
Se non vi piace l'esempio del campione di sangue,lo stesso tipo di ragionamento può essere applicato all'automobile consegnata al garage per una riparazione.<br />
Ciò potrebbe consistere in<br />
*Il veicolo fisico<br />
*i documenti in possesso del proprietario: Libretto di circolazione (comprese targhe), le assicurazioni, le ricevute per l'acquisto, i pezzi di ricambio, le riparazioni, ecc<br />
*il consumo di carburante<br />
*i conducenti autorizzati ad utilizzare il veicolo, con le loro patenti di guida<br />
*gli interventi di manutenzione registrati presso il garage<br />
*metodi o procedure da seguire per la verifica e la manutenzione di routine<br />
*metodi da seguire per le riparazioni non di routine, ecc<br />
*informazioni di fatturazione per il cliente<br />
<br />
== Esempi di programmazione ==<br />
<br />
Basta con questa introduzione, fatta di esempi del mondo reale! Dobbiamo procedere con l'obiettivo principale: la programmazione FreePascal<br />
<br />
<br />
<br />
Dobbiamo considerare la creazione di un semplice modulo con pochi controlli per una applicazione in FreePascal / Lazzaro.<br />
<br />
<div class="floatleft">[[Image:ObjectInspector-TForm.png]]</div><br />
<div class="floatright">[[Image:BlankForm.png]]</div><br />
<br />
<br />
Richiamando la IDE di Lazarus, al programmatore viene presentato un modello vuoto "Form" in progettazione, in cui egli dovrà porre oggetti e vari controlli.<br />
<br />
Si noti che il Form vuoto precostituito è già un oggetto, con le proprie caratteristiche, come la posizione (in alto e sinistra), le dimensioni (altezza e larghezza), il colore, il font di default per l'aggiunta di testo ecc<br />
<br />
<br />
<br />
----<br />
<br />
<br />
Se un controllo Button, un tasto, viene immesso sul Form (tipo TButton), questi avrà una serie di proprietà, che possono essere esaminate nella finestra Object Inspector .<br />
<br />
<br />
Molte delle proprietà hanno nomi simili a quelle del Modulo 'Form', questo è dovuto al fatto che molte proprietà sono'' 'ereditate''' da parte di alcuni comuni antenati di classe, che definiscono le proprietà come sono definite e gestite dalle classi discendenti. <br />
<br />
Così come per le proprietà, l'Object Inspector offre una scheda denominata'' 'Eventi''', che dà accesso ai gestori di eventi 'Event Handlers' che sono metodi per gestire tali eventi, come un clic del mouse su un pulsante (OnClick) o alcuni cambiamento di posizione, le dimensioni o altre proprietà (OnChange).<br />
<br />
L'immagine fisica del pulsante nel Modulo o Form, insieme con tutte le sue proprietà e metodi di gestione, dovrebbe essere considerato come una singola entità o'' 'oggetto''' in Pascal.<br />
<br />
<div class="floatleft">[[Image:ObjectInspector-TButton.png]]</div><br />
<div class="floatright">[[Image:FormWithButton.png]]</div><br />
<div class="floatright">[[Image:Source_FormWithButton1.png ]]</div><br />
<br />
== Object-Oriented Extensions to standard Pascal ==<br />
<br />
La struttura Pascal di tipo record viene estesa per definire un<br />
=== Object ===<br />
<br />
Un oggetto è uno speciale tipo di record. Il record contiene tutti i campi che sono dichiarati nella definizione dell'oggetto (proprio come un convenzionale record), ma ora le procedure e le funzioni possono essere dichiarate come se fossero parte del record e si richiamano come puntatori ai metodi associati con il tipo di oggetto.<br />
<br />
Ad esempio, un oggetto può contenere una serie di valori reali, una matrice,unitamente con un metodo di calcolo della media.<br />
<br />
Type<br />
Average = Object<br />
NumVal: Integer;<br />
Values: Array [1..200] of Real;<br />
Function Mean: Real; { calculates the average value of the array }<br />
End;<br />
<br />
Gli oggetti possono "ereditare" campi e metodi da oggetti "madre". Ciò significa che questi campi e metodi possono essere usati come se fossero incluse negli oggetti dichiarati come un oggetto figlio.<br />
<br />
Inoltre, viene introdotto un concetto di visibilità : i campi, le procedure e le funzioni possono essere dichiarati come pubblici, protetti o privati. Per impostazione predefinita, i campi e metodi sono pubblici, e possono essere esportati al di fuori delle attuali unit. Campi o metodi protetti sono disponibili solo per gli oggetti discendenti dal corrente oggetto antenato. Campi e metodi dichiarati privati sono unicamente accessibili nella unit corrente:<br />
il loro scopo è limitato all'implementazione della corrente unit.<br />
<br />
=== Class ===<br />
Gli oggetti molto spesso non sono usati da se stessi in FreePascal and Lazarus; invece le classi sono largamente usate.<br />
La Classe è definita quasi alla stessa stregua di un oggetto, ma è un puntatore ad un oggetto piuttosto che l'oggetto stesso.<br />
Technically, this means that the Class is allocated on the Heap of a program, whereas the Object is allocated on the Stack.<br />
Tecnicamente, questo significa che la classe è assegnata "on the Heap of a program", mentre l'oggetto viene assegnato in Stack<br />
<br />
Here is a simple example of a typical Class declaration:<br />
{-----------------------------------------}<br />
{example of Class declaration from the LCL}<br />
{-----------------------------------------}<br />
TPen = class(TFPCustomPen)<br />
private<br />
FColor: TColor;<br />
FPenHandleCached: boolean;<br />
FReference: TWSPenReference;<br />
procedure FreeReference;<br />
function GetHandle: HPEN;<br />
function GetReference: TWSPenReference;<br />
procedure ReferenceNeeded;<br />
procedure SetHandle(const Value: HPEN);<br />
protected<br />
procedure DoAllocateResources; override;<br />
procedure DoDeAllocateResources; override;<br />
procedure DoCopyProps(From: TFPCanvasHelper); override;<br />
procedure SetColor<br />
(const NewColor: TColor; const NewFPColor: TFPColor); virtual;<br />
procedure SetFPColor(const AValue: TFPColor); override;<br />
procedure SetColor(Value: TColor);<br />
procedure SetMode(Value: TPenMode); override;<br />
procedure SetStyle(Value: TPenStyle); override;<br />
procedure SetWidth(value: Integer); override;<br />
public<br />
constructor Create; override;<br />
destructor Destroy; override;<br />
procedure Assign(Source: TPersistent); override;<br />
property Handle: HPEN read GetHandle write SetHandle; deprecated;<br />
property Reference: TWSPenReference read GetReference;<br />
published<br />
property Color: TColor read FColor write SetColor default clBlack;<br />
property Mode default pmCopy;<br />
property Style default psSolid;<br />
property Width default 1;<br />
end;<br />
<br />
<br />
Note that this class is defined as an instance of another '''parent''' or '''ancestor''' class (''TFPCustomPen'') from which it '''inherits''' all its properties and methods. It has some fields of its own, grouped under<br />
*'''private''' - this means that items defined here are only available or visible to other classes or procedures/function defined within the same program unit (this example is from ''Graphics'', so any of the other classes such as ''TBitMap'', ''TPicture'' etc in the same unit can use them). They are essentially local variables (eg ''FColor'', ''FPenHandleCached'') or locally used methods (''GetHandle'', ''SetHandle'') but can be used or referred to in items declared in the '''protected''' or '''public''' sections.<br />
*'''protected''' - this means that items defined here are only available or visible to classes that are descended from this '''ancestor''' class, and inherit its properties or methods<br />
*'''public''' - this means that items defined here are available to any programming unit that includes the current unit in its [[Glossary#Uses | Uses]] clause <br />
*'''published''' - is the same as a '''public''' section, but the compiler also generates type information that is needed for automatic streaming of these classes. Often the list of published items appear in the Object Inspector of Lazarus; if there is no '''published''' list, all the '''public''' fields usually appear in the Object Inspector.<br />
<br />
=== Methods ===<br />
A method is just like a standard procedure or function, but can have some additional '''directives'''.<br />
<br />
Some of the methods defined above are labelled with the directive '''virtual'''; others are labelled with the '''override''' directive.<br />
*'''virtual''' means that the type or actual instance of a method is not known at compile-time, but is selected at run-time depending on what sub-program actually calls the method. It could be considered a place-holder in the definition of the class.<br />
*'''override''' means that at run-time the locally given definition can take the place of a definition inherited from an ancestor class, particularly if it was '''virtual'''. If you particularly want to use the method defined in the ancestor class, it is sometimes necessary to call it specifically with the '''inherited''' clause.<br />
<br />
Methods with no virtual or override directive are '''static''' methods (the usual kind in Pascal). Those with a virtual or override directive are '''dynamic'''.<br />
<br />
Special instances of methods are:<br />
*'''create''' - a '''constructor''' for a class, which takes care of allocating memory, collecting together all the information needed and configuring/initializing the various properties.<br />
*'''destroy''' - a '''destructor''' for a class, which removes all the parts of the class from the system in an orderly and logical way, and returns all its resources for the system to re-use.<br />
<br />
=== Properties ===<br />
<br />
Properties are just like ordinary fields in a conventional Pascal record, but they can have '''read''' and/or '''write''' specifiers.<br />
*'''read''' specifier is a field, or a function that returns a result of the correct type for the property. In the example above, the property ''Color'' has a read specifier ''FColor'', which is a local variable containing the value to be used. If a property has a '''read''' but no '''write''' specifier, it is read-only.<br />
*'''write''' specifier is a field, or a procedure that will store the value of the property in a specific location. In the example above, ''Color'' has a write specifier ''SetColor'' that is a procedure (defined in the '''protected''' section) for writing the color value to some specified location. If a property has a '''write''' but no '''read''' specifier, it is write-only.<br />
*'''default''' - note that it is possible to set a '''default''' value for a property. For example, ''Color'' here is given the default value ''clBlack'', or black, at the time of creation. It could subsequently be given a different value, by a programming assignment statement, or in the Object Inspector.<br />
<br />
== Further information ==<br />
<br />
This has only scratched the surface of the topic. For more details, readers are strongly recommended to read the [http://lazarus-ccr.sourceforge.net/fpcdoc/ref/ref.html FreePascal] manuals, especially Chapters 5 ('''Objects''') and 6 ('''Classes''')<br />
<br />
--[[User:Kirkpatc|Kirkpatc]] 11:04, 20 July 2008 (CEST)<br />
<br />
----<br />
[[Console Mode Pascal]]</div>Amedeohttps://wiki.freepascal.org/index.php?title=Object_Oriented_Programming_with_Free_Pascal_and_Lazarus/it&diff=34769Object Oriented Programming with Free Pascal and Lazarus/it2009-04-01T09:28:07Z<p>Amedeo: /* Object */</p>
<hr />
<div>{{Object_Oriented_Programming_with_FreePascal_and_Lazarus}}<br />
<br />
Esistono molte guide eccellenti su Pascal, ma questa guida tenta di coinvolgere ulteriormente il principiante , nella programmazione orientata agli oggetti o [[Glossary#OO | Object-Oriented Programming]], che è un'estensione dello standard pascal, offerta da Turbo pascal, Delphi e FreePascal/Lazarus.<br />
<br />
Un [[Glossary#Object | Object]] è un'estensione della struttura standard pascal detta [http://wiki.lazarus.freepascal.org/Record record]<br />
<br />
La programmazione Pascal in testo standard è adatta alla creazione di applicazioni che, come le applicazioni Unix tradizionali,sono adatte per fare una cosa e per farla molto bene.<br />
<br />
Ciò che un programma fa può essere un'azione veramente complicata ,e può offrire all'utente molte opzioni di menu,<br />
ma è essenzialmente ristretta ad obbedire a comandi che l'utente digita da tastiera e a listare le sue risposte sul terminale o sulla stampante. <br />
<br />
Per poter produrre una [[Glossary#GUI | Graphical User Interface (GUI)]] usualmente si utilizza una sorta di Metodo di programmazione orientata agli oggetti (spesso facendo uso di [[Glossary#C Programming Language | C]] o di una delle sue varianti, o Visual Basic, o una delle [[Glossary#OO | OO]] varianti di Pascal quali [[Glossary#FreePascal | FreePascal]] con o senza [[Glossary#Lazarus | Lazarus]]). <br />
<br />
In una GUI all'utente vengono presentate schermate con un gran numero di immagini organizzate in modo strutturato, consistenti in un'insieme di strumenti o [[Glossary#Widget | Widgets]] che sono associati con varie azioni quali <br />
*selezioni da menu, <br />
*aperture o salvataggio files , <br />
*connessioni ad Internet, <br />
*esecuzioni di calcoli numerici, etc. <br />
<br />
L'utente dovrà muovere il mouse o qualche altro puntatore o strumento sullo schermo, per selezionare le azioni che saranno eseguite in risposta al click del mouse o ai tasti premuti.<br />
<br />
I sistemi per offrire una complessa interfaccia grafica possono essere scritti in Pascal standard o quasi qualsiasi altro linguaggio di programmazione, ma è molto più facile l'utilizzo di un sistema orientato agli oggetti, in cui ogni oggetto grafico sullo schermo può avere tutte le sue proprietà e le sue procedure e funzioni connesse con il suo uso conglobate in una struttura comune.<br />
<br />
<br />
== Oggetti - una analogia con il mondo reale == <br />
Consideriamo le analogie di un campione di sangue prelevato in un ospedale o in uno studio medico.<br />
=== Campione di sangue ===<br />
Il campione fisico è certamente un oggetto o '''object'''; ed ha , associato con esso una quantità di informazioni,documenti ed altri oggetti fisici. <br />
<br />
*'''Provetta''', del tipo determinato dal test che si dovrà eseguire.<br />
<br />
*'''Metodica''' (o ''metodo'', ''procedura operativa standard'') utilizzata dall'infermiera o dal tecnico di laboratorio che prelevano e processano il campione <br />
** che tipo di provetta si dovrà usare, <br />
**come processare il campione<br />
**come conservarlo prima di consegnarlo al laboratorio. <br />
<br />
*'''Etichetta''' sulla provetta con i dettagli per <br />
**identificare il campione <br />
**Nome e cognome e data di nascita del paziente <br />
** data e ora del prelievo <br />
** analisi richieste. <br />
<br />
*'''Modulo di richiesta''' che accompagna il campione per il laboratorio cui il campione è diretto <br />
** ID Campione<br />
**ID del medico richiedente<br />
** quali analisi il medico richiede e <br />
**anamnesi e dettagli completi del paziente<br />
**La possibile diagnosi di cui si richiede conferma. <br />
<br />
<br />
Una copia delle richiesta viene conservata nella cartella clinica per ricordare al medico di attendersi risultati entro un periodo di tempo adeguato. <br />
<br />
<br />
*In laboratorio - '''metodi locali''' per determinare <br />
**come il campione deve essere analizzato, <br />
**Quale strumento usare, <br />
**come lo strumento dovrà operare e come dovrà essere calibrato, <br />
**come il risultato dovrà essere memorizzato formattato e <br />
**presentato al medico. <br />
<br />
L'effettivo'' 'risultato''' è un dato che il medico usa per formulare la diagnosi, e una copia dei risultati è archiviata nella cartella clinica del paziente.<br />
<br />
Il campione fisico può essere conservato per riferimento,per test di conferma o ulteriori test, o potrà essere smaltito in ottemperanza alle norme per lo smaltimento dei campioni biologici o mediante incenerimento, ci sarà un metodo per descrivere questo procedimento.<br />
<br />
<br />
Non è necessario che il medico dica tutti i dettagli operativi e le istruzioni di lavoro ogni qualvolta che un campione viene prelevato; anzi,egli può avere ben poche conoscenze di come il campione verrà processato dal laboratorio. <br />
<br />
I dettagli dei vari processi sono'' '''ereditati''' dai precedenti processi dei campione in analisi ,ossia a priori si è stabilito il metodo di processo del campione - ci sarà un piano generico per l'intera sequenza, e insieme abbiamo potuto pensare al campione di sangue,a tutti i suoi documenti e dati, e la metodica di base, come a un complesso'' 'oggetto'''.<br />
<br />
<br />
<br />
Nella mente del medico, il campione di sangue è visto come un'unica entità, come i suoi risultati, e per gli infermieri e tecnici il campione, la provetta, l'etichetta e le condizioni di conservazione anch'esse sono identificate come se fossero una sola entità.<br />
<br />
Traduzione da completare.....<br />
<br />
=== Un'altro esempio- Automobile ===<br />
Se non vi piace l'esempio del campione di sangue,lo stesso tipo di ragionamento può essere applicato all'automobile consegnata al garage per una riparazione.<br />
Ciò potrebbe consistere in<br />
*Il veicolo fisico<br />
*i documenti in possesso del proprietario: Libretto di circolazione (comprese targhe), le assicurazioni, le ricevute per l'acquisto, i pezzi di ricambio, le riparazioni, ecc<br />
*il consumo di carburante<br />
*i conducenti autorizzati ad utilizzare il veicolo, con le loro patenti di guida<br />
*gli interventi di manutenzione registrati presso il garage<br />
*metodi o procedure da seguire per la verifica e la manutenzione di routine<br />
*metodi da seguire per le riparazioni non di routine, ecc<br />
*informazioni di fatturazione per il cliente<br />
<br />
== Esempi di programmazione ==<br />
<br />
Basta con questa introduzione, fatta di esempi del mondo reale! Dobbiamo procedere con l'obiettivo principale: la programmazione FreePascal<br />
<br />
<br />
<br />
Dobbiamo considerare la creazione di un semplice modulo con pochi controlli per una applicazione in FreePascal / Lazzaro.<br />
<br />
<div class="floatleft">[[Image:ObjectInspector-TForm.png]]</div><br />
<div class="floatright">[[Image:BlankForm.png]]</div><br />
<br />
<br />
Richiamando la IDE di Lazarus, al programmatore viene presentato un modello vuoto "Form" in progettazione, in cui egli dovrà porre oggetti e vari controlli.<br />
<br />
Si noti che il Form vuoto precostituito è già un oggetto, con le proprie caratteristiche, come la posizione (in alto e sinistra), le dimensioni (altezza e larghezza), il colore, il font di default per l'aggiunta di testo ecc<br />
<br />
<br />
<br />
----<br />
<br />
<br />
Se un controllo Button, un tasto, viene immesso sul Form (tipo TButton), questi avrà una serie di proprietà, che possono essere esaminate nella finestra Object Inspector .<br />
<br />
<br />
Molte delle proprietà hanno nomi simili a quelle del Modulo 'Form', questo è dovuto al fatto che molte proprietà sono'' 'ereditate''' da parte di alcuni comuni antenati di classe, che definiscono le proprietà come sono definite e gestite dalle classi discendenti. <br />
<br />
Così come per le proprietà, l'Object Inspector offre una scheda denominata'' 'Eventi''', che dà accesso ai gestori di eventi 'Event Handlers' che sono metodi per gestire tali eventi, come un clic del mouse su un pulsante (OnClick) o alcuni cambiamento di posizione, le dimensioni o altre proprietà (OnChange).<br />
<br />
L'immagine fisica del pulsante nel Modulo o Form, insieme con tutte le sue proprietà e metodi di gestione, dovrebbe essere considerato come una singola entità o'' 'oggetto''' in Pascal.<br />
<br />
<div class="floatleft">[[Image:ObjectInspector-TButton.png]]</div><br />
<div class="floatright">[[Image:FormWithButton.png]]</div><br />
<div class="floatright">[[Image:Source_FormWithButton1.png ]]</div><br />
<br />
== Object-Oriented Extensions to standard Pascal ==<br />
<br />
La struttura Pascal di tipo record viene estesa per definire un<br />
=== Object ===<br />
<br />
Un oggetto è uno speciale tipo di record. Il record contiene tutti i campi che sono dichiarati nella definizione dell'oggetto (proprio come un convenzionale record), ma ora le procedure e le funzioni possono essere dichiarate come se fossero parte del record e si richiamano come puntatori ai metodi associati con il tipo di oggetto.<br />
<br />
Ad esempio, un oggetto può contenere una serie di valori reali, una matrice,unitamente con un metodo di calcolo della media.<br />
<br />
Type<br />
Average = Object<br />
NumVal: Integer;<br />
Values: Array [1..200] of Real;<br />
Function Mean: Real; { calculates the average value of the array }<br />
End;<br />
<br />
Gli oggetti possono "ereditare" campi e metodi da oggetti "madre". Ciò significa che questi campi e metodi possono essere usati come se fossero incluse negli oggetti dichiarati come un oggetto figlio.<br />
<br />
Inoltre, viene introdotto un concetto di visibilità : i campi, le procedure e le funzioni possono essere dichiarati come pubblici, protetti o privati. Per impostazione predefinita, i campi e metodi sono pubblici, e possono essere esportati al di fuori delle attuali unit. Campi o metodi protetti sono disponibili solo per gli oggetti discendenti dal corrente oggetto antenato. Campi e metodi dichiarati privati sono unicamente accessibili nella unit corrente:<br />
il loro scopo è limitato all'implementazione della corrente unit.<br />
<br />
=== Class ===<br />
Objects are not used very often by themselves in FreePascal and Lazarus; instead, Classes are used very widely. A Class is defined in almost the same way as an Object, but is a pointer to an Object rather than the Object itself. Technically, this means that the Class is allocated on the Heap of a program, whereas the Object is allocated on the Stack.<br />
<br />
Here is a simple example of a typical Class declaration:<br />
{-----------------------------------------}<br />
{example of Class declaration from the LCL}<br />
{-----------------------------------------}<br />
TPen = class(TFPCustomPen)<br />
private<br />
FColor: TColor;<br />
FPenHandleCached: boolean;<br />
FReference: TWSPenReference;<br />
procedure FreeReference;<br />
function GetHandle: HPEN;<br />
function GetReference: TWSPenReference;<br />
procedure ReferenceNeeded;<br />
procedure SetHandle(const Value: HPEN);<br />
protected<br />
procedure DoAllocateResources; override;<br />
procedure DoDeAllocateResources; override;<br />
procedure DoCopyProps(From: TFPCanvasHelper); override;<br />
procedure SetColor<br />
(const NewColor: TColor; const NewFPColor: TFPColor); virtual;<br />
procedure SetFPColor(const AValue: TFPColor); override;<br />
procedure SetColor(Value: TColor);<br />
procedure SetMode(Value: TPenMode); override;<br />
procedure SetStyle(Value: TPenStyle); override;<br />
procedure SetWidth(value: Integer); override;<br />
public<br />
constructor Create; override;<br />
destructor Destroy; override;<br />
procedure Assign(Source: TPersistent); override;<br />
property Handle: HPEN read GetHandle write SetHandle; deprecated;<br />
property Reference: TWSPenReference read GetReference;<br />
published<br />
property Color: TColor read FColor write SetColor default clBlack;<br />
property Mode default pmCopy;<br />
property Style default psSolid;<br />
property Width default 1;<br />
end;<br />
<br />
<br />
Note that this class is defined as an instance of another '''parent''' or '''ancestor''' class (''TFPCustomPen'') from which it '''inherits''' all its properties and methods. It has some fields of its own, grouped under<br />
*'''private''' - this means that items defined here are only available or visible to other classes or procedures/function defined within the same program unit (this example is from ''Graphics'', so any of the other classes such as ''TBitMap'', ''TPicture'' etc in the same unit can use them). They are essentially local variables (eg ''FColor'', ''FPenHandleCached'') or locally used methods (''GetHandle'', ''SetHandle'') but can be used or referred to in items declared in the '''protected''' or '''public''' sections.<br />
*'''protected''' - this means that items defined here are only available or visible to classes that are descended from this '''ancestor''' class, and inherit its properties or methods<br />
*'''public''' - this means that items defined here are available to any programming unit that includes the current unit in its [[Glossary#Uses | Uses]] clause <br />
*'''published''' - is the same as a '''public''' section, but the compiler also generates type information that is needed for automatic streaming of these classes. Often the list of published items appear in the Object Inspector of Lazarus; if there is no '''published''' list, all the '''public''' fields usually appear in the Object Inspector.<br />
<br />
=== Methods ===<br />
A method is just like a standard procedure or function, but can have some additional '''directives'''.<br />
<br />
Some of the methods defined above are labelled with the directive '''virtual'''; others are labelled with the '''override''' directive.<br />
*'''virtual''' means that the type or actual instance of a method is not known at compile-time, but is selected at run-time depending on what sub-program actually calls the method. It could be considered a place-holder in the definition of the class.<br />
*'''override''' means that at run-time the locally given definition can take the place of a definition inherited from an ancestor class, particularly if it was '''virtual'''. If you particularly want to use the method defined in the ancestor class, it is sometimes necessary to call it specifically with the '''inherited''' clause.<br />
<br />
Methods with no virtual or override directive are '''static''' methods (the usual kind in Pascal). Those with a virtual or override directive are '''dynamic'''.<br />
<br />
Special instances of methods are:<br />
*'''create''' - a '''constructor''' for a class, which takes care of allocating memory, collecting together all the information needed and configuring/initializing the various properties.<br />
*'''destroy''' - a '''destructor''' for a class, which removes all the parts of the class from the system in an orderly and logical way, and returns all its resources for the system to re-use.<br />
<br />
=== Properties ===<br />
<br />
Properties are just like ordinary fields in a conventional Pascal record, but they can have '''read''' and/or '''write''' specifiers.<br />
*'''read''' specifier is a field, or a function that returns a result of the correct type for the property. In the example above, the property ''Color'' has a read specifier ''FColor'', which is a local variable containing the value to be used. If a property has a '''read''' but no '''write''' specifier, it is read-only.<br />
*'''write''' specifier is a field, or a procedure that will store the value of the property in a specific location. In the example above, ''Color'' has a write specifier ''SetColor'' that is a procedure (defined in the '''protected''' section) for writing the color value to some specified location. If a property has a '''write''' but no '''read''' specifier, it is write-only.<br />
*'''default''' - note that it is possible to set a '''default''' value for a property. For example, ''Color'' here is given the default value ''clBlack'', or black, at the time of creation. It could subsequently be given a different value, by a programming assignment statement, or in the Object Inspector.<br />
<br />
== Further information ==<br />
<br />
This has only scratched the surface of the topic. For more details, readers are strongly recommended to read the [http://lazarus-ccr.sourceforge.net/fpcdoc/ref/ref.html FreePascal] manuals, especially Chapters 5 ('''Objects''') and 6 ('''Classes''')<br />
<br />
--[[User:Kirkpatc|Kirkpatc]] 11:04, 20 July 2008 (CEST)<br />
<br />
----<br />
[[Console Mode Pascal]]</div>Amedeohttps://wiki.freepascal.org/index.php?title=Object_Oriented_Programming_with_Free_Pascal_and_Lazarus/it&diff=34768Object Oriented Programming with Free Pascal and Lazarus/it2009-04-01T09:19:24Z<p>Amedeo: /* Object */</p>
<hr />
<div>{{Object_Oriented_Programming_with_FreePascal_and_Lazarus}}<br />
<br />
Esistono molte guide eccellenti su Pascal, ma questa guida tenta di coinvolgere ulteriormente il principiante , nella programmazione orientata agli oggetti o [[Glossary#OO | Object-Oriented Programming]], che è un'estensione dello standard pascal, offerta da Turbo pascal, Delphi e FreePascal/Lazarus.<br />
<br />
Un [[Glossary#Object | Object]] è un'estensione della struttura standard pascal detta [http://wiki.lazarus.freepascal.org/Record record]<br />
<br />
La programmazione Pascal in testo standard è adatta alla creazione di applicazioni che, come le applicazioni Unix tradizionali,sono adatte per fare una cosa e per farla molto bene.<br />
<br />
Ciò che un programma fa può essere un'azione veramente complicata ,e può offrire all'utente molte opzioni di menu,<br />
ma è essenzialmente ristretta ad obbedire a comandi che l'utente digita da tastiera e a listare le sue risposte sul terminale o sulla stampante. <br />
<br />
Per poter produrre una [[Glossary#GUI | Graphical User Interface (GUI)]] usualmente si utilizza una sorta di Metodo di programmazione orientata agli oggetti (spesso facendo uso di [[Glossary#C Programming Language | C]] o di una delle sue varianti, o Visual Basic, o una delle [[Glossary#OO | OO]] varianti di Pascal quali [[Glossary#FreePascal | FreePascal]] con o senza [[Glossary#Lazarus | Lazarus]]). <br />
<br />
In una GUI all'utente vengono presentate schermate con un gran numero di immagini organizzate in modo strutturato, consistenti in un'insieme di strumenti o [[Glossary#Widget | Widgets]] che sono associati con varie azioni quali <br />
*selezioni da menu, <br />
*aperture o salvataggio files , <br />
*connessioni ad Internet, <br />
*esecuzioni di calcoli numerici, etc. <br />
<br />
L'utente dovrà muovere il mouse o qualche altro puntatore o strumento sullo schermo, per selezionare le azioni che saranno eseguite in risposta al click del mouse o ai tasti premuti.<br />
<br />
I sistemi per offrire una complessa interfaccia grafica possono essere scritti in Pascal standard o quasi qualsiasi altro linguaggio di programmazione, ma è molto più facile l'utilizzo di un sistema orientato agli oggetti, in cui ogni oggetto grafico sullo schermo può avere tutte le sue proprietà e le sue procedure e funzioni connesse con il suo uso conglobate in una struttura comune.<br />
<br />
<br />
== Oggetti - una analogia con il mondo reale == <br />
Consideriamo le analogie di un campione di sangue prelevato in un ospedale o in uno studio medico.<br />
=== Campione di sangue ===<br />
Il campione fisico è certamente un oggetto o '''object'''; ed ha , associato con esso una quantità di informazioni,documenti ed altri oggetti fisici. <br />
<br />
*'''Provetta''', del tipo determinato dal test che si dovrà eseguire.<br />
<br />
*'''Metodica''' (o ''metodo'', ''procedura operativa standard'') utilizzata dall'infermiera o dal tecnico di laboratorio che prelevano e processano il campione <br />
** che tipo di provetta si dovrà usare, <br />
**come processare il campione<br />
**come conservarlo prima di consegnarlo al laboratorio. <br />
<br />
*'''Etichetta''' sulla provetta con i dettagli per <br />
**identificare il campione <br />
**Nome e cognome e data di nascita del paziente <br />
** data e ora del prelievo <br />
** analisi richieste. <br />
<br />
*'''Modulo di richiesta''' che accompagna il campione per il laboratorio cui il campione è diretto <br />
** ID Campione<br />
**ID del medico richiedente<br />
** quali analisi il medico richiede e <br />
**anamnesi e dettagli completi del paziente<br />
**La possibile diagnosi di cui si richiede conferma. <br />
<br />
<br />
Una copia delle richiesta viene conservata nella cartella clinica per ricordare al medico di attendersi risultati entro un periodo di tempo adeguato. <br />
<br />
<br />
*In laboratorio - '''metodi locali''' per determinare <br />
**come il campione deve essere analizzato, <br />
**Quale strumento usare, <br />
**come lo strumento dovrà operare e come dovrà essere calibrato, <br />
**come il risultato dovrà essere memorizzato formattato e <br />
**presentato al medico. <br />
<br />
L'effettivo'' 'risultato''' è un dato che il medico usa per formulare la diagnosi, e una copia dei risultati è archiviata nella cartella clinica del paziente.<br />
<br />
Il campione fisico può essere conservato per riferimento,per test di conferma o ulteriori test, o potrà essere smaltito in ottemperanza alle norme per lo smaltimento dei campioni biologici o mediante incenerimento, ci sarà un metodo per descrivere questo procedimento.<br />
<br />
<br />
Non è necessario che il medico dica tutti i dettagli operativi e le istruzioni di lavoro ogni qualvolta che un campione viene prelevato; anzi,egli può avere ben poche conoscenze di come il campione verrà processato dal laboratorio. <br />
<br />
I dettagli dei vari processi sono'' '''ereditati''' dai precedenti processi dei campione in analisi ,ossia a priori si è stabilito il metodo di processo del campione - ci sarà un piano generico per l'intera sequenza, e insieme abbiamo potuto pensare al campione di sangue,a tutti i suoi documenti e dati, e la metodica di base, come a un complesso'' 'oggetto'''.<br />
<br />
<br />
<br />
Nella mente del medico, il campione di sangue è visto come un'unica entità, come i suoi risultati, e per gli infermieri e tecnici il campione, la provetta, l'etichetta e le condizioni di conservazione anch'esse sono identificate come se fossero una sola entità.<br />
<br />
Traduzione da completare.....<br />
<br />
=== Un'altro esempio- Automobile ===<br />
Se non vi piace l'esempio del campione di sangue,lo stesso tipo di ragionamento può essere applicato all'automobile consegnata al garage per una riparazione.<br />
Ciò potrebbe consistere in<br />
*Il veicolo fisico<br />
*i documenti in possesso del proprietario: Libretto di circolazione (comprese targhe), le assicurazioni, le ricevute per l'acquisto, i pezzi di ricambio, le riparazioni, ecc<br />
*il consumo di carburante<br />
*i conducenti autorizzati ad utilizzare il veicolo, con le loro patenti di guida<br />
*gli interventi di manutenzione registrati presso il garage<br />
*metodi o procedure da seguire per la verifica e la manutenzione di routine<br />
*metodi da seguire per le riparazioni non di routine, ecc<br />
*informazioni di fatturazione per il cliente<br />
<br />
== Esempi di programmazione ==<br />
<br />
Basta con questa introduzione, fatta di esempi del mondo reale! Dobbiamo procedere con l'obiettivo principale: la programmazione FreePascal<br />
<br />
<br />
<br />
Dobbiamo considerare la creazione di un semplice modulo con pochi controlli per una applicazione in FreePascal / Lazzaro.<br />
<br />
<div class="floatleft">[[Image:ObjectInspector-TForm.png]]</div><br />
<div class="floatright">[[Image:BlankForm.png]]</div><br />
<br />
<br />
Richiamando la IDE di Lazarus, al programmatore viene presentato un modello vuoto "Form" in progettazione, in cui egli dovrà porre oggetti e vari controlli.<br />
<br />
Si noti che il Form vuoto precostituito è già un oggetto, con le proprie caratteristiche, come la posizione (in alto e sinistra), le dimensioni (altezza e larghezza), il colore, il font di default per l'aggiunta di testo ecc<br />
<br />
<br />
<br />
----<br />
<br />
<br />
Se un controllo Button, un tasto, viene immesso sul Form (tipo TButton), questi avrà una serie di proprietà, che possono essere esaminate nella finestra Object Inspector .<br />
<br />
<br />
Molte delle proprietà hanno nomi simili a quelle del Modulo 'Form', questo è dovuto al fatto che molte proprietà sono'' 'ereditate''' da parte di alcuni comuni antenati di classe, che definiscono le proprietà come sono definite e gestite dalle classi discendenti. <br />
<br />
Così come per le proprietà, l'Object Inspector offre una scheda denominata'' 'Eventi''', che dà accesso ai gestori di eventi 'Event Handlers' che sono metodi per gestire tali eventi, come un clic del mouse su un pulsante (OnClick) o alcuni cambiamento di posizione, le dimensioni o altre proprietà (OnChange).<br />
<br />
L'immagine fisica del pulsante nel Modulo o Form, insieme con tutte le sue proprietà e metodi di gestione, dovrebbe essere considerato come una singola entità o'' 'oggetto''' in Pascal.<br />
<br />
<div class="floatleft">[[Image:ObjectInspector-TButton.png]]</div><br />
<div class="floatright">[[Image:FormWithButton.png]]</div><br />
<div class="floatright">[[Image:Source_FormWithButton1.png ]]</div><br />
<br />
== Object-Oriented Extensions to standard Pascal ==<br />
<br />
La struttura Pascal di tipo record viene estesa per definire un<br />
=== Object ===<br />
<br />
Un oggetto è uno speciale tipo di record. Il record contiene tutti i campi che sono dichiarati nella definizione dell'oggetto (proprio come un convenzionale record), ma ora le procedure e le funzioni possono essere dichiarate come se fossero parte del record e si richiamano come puntatori ai metodi associati con il tipo di oggetto.<br />
<br />
Ad esempio, un oggetto può contenere una serie di valori reali, una matrice,unitamente con un metodo di calcolo della media.<br />
<br />
Type<br />
Average = Object<br />
NumVal: Integer;<br />
Values: Array [1..200] of Real;<br />
Function Mean: Real; { calculates the average value of the array }<br />
End;<br />
<br />
Gli oggetti possono "ereditare" campi e metodi da oggetti "madre". Ciò significa che questi campi e metodi possono essere usati come se fossero incluse negli oggetti dichiarati come un oggetto figlio.<br />
<br />
<br />
Inoltre, viene introdotto un concetto di visibilità : i campi, le procedure e le funzioni possono essere dichiarati come pubblici, protetti o privati. Per impostazione predefinita, i campi e metodi sono pubblici, e possono essere esportati al di fuori delle attuali unit. Campi o metodi protetti sono disponibili solo per gli oggetti discescendenti dal corrente antenato oggetto.Protected fields or methods are available only to objects descended from the current ancestor object. Fields or methods that are declared private are only accessible in the current unit:<br />
their scope is limited to the implementation of the current unit.<br />
<br />
=== Class ===<br />
Objects are not used very often by themselves in FreePascal and Lazarus; instead, Classes are used very widely. A Class is defined in almost the same way as an Object, but is a pointer to an Object rather than the Object itself. Technically, this means that the Class is allocated on the Heap of a program, whereas the Object is allocated on the Stack.<br />
<br />
Here is a simple example of a typical Class declaration:<br />
{-----------------------------------------}<br />
{example of Class declaration from the LCL}<br />
{-----------------------------------------}<br />
TPen = class(TFPCustomPen)<br />
private<br />
FColor: TColor;<br />
FPenHandleCached: boolean;<br />
FReference: TWSPenReference;<br />
procedure FreeReference;<br />
function GetHandle: HPEN;<br />
function GetReference: TWSPenReference;<br />
procedure ReferenceNeeded;<br />
procedure SetHandle(const Value: HPEN);<br />
protected<br />
procedure DoAllocateResources; override;<br />
procedure DoDeAllocateResources; override;<br />
procedure DoCopyProps(From: TFPCanvasHelper); override;<br />
procedure SetColor<br />
(const NewColor: TColor; const NewFPColor: TFPColor); virtual;<br />
procedure SetFPColor(const AValue: TFPColor); override;<br />
procedure SetColor(Value: TColor);<br />
procedure SetMode(Value: TPenMode); override;<br />
procedure SetStyle(Value: TPenStyle); override;<br />
procedure SetWidth(value: Integer); override;<br />
public<br />
constructor Create; override;<br />
destructor Destroy; override;<br />
procedure Assign(Source: TPersistent); override;<br />
property Handle: HPEN read GetHandle write SetHandle; deprecated;<br />
property Reference: TWSPenReference read GetReference;<br />
published<br />
property Color: TColor read FColor write SetColor default clBlack;<br />
property Mode default pmCopy;<br />
property Style default psSolid;<br />
property Width default 1;<br />
end;<br />
<br />
<br />
Note that this class is defined as an instance of another '''parent''' or '''ancestor''' class (''TFPCustomPen'') from which it '''inherits''' all its properties and methods. It has some fields of its own, grouped under<br />
*'''private''' - this means that items defined here are only available or visible to other classes or procedures/function defined within the same program unit (this example is from ''Graphics'', so any of the other classes such as ''TBitMap'', ''TPicture'' etc in the same unit can use them). They are essentially local variables (eg ''FColor'', ''FPenHandleCached'') or locally used methods (''GetHandle'', ''SetHandle'') but can be used or referred to in items declared in the '''protected''' or '''public''' sections.<br />
*'''protected''' - this means that items defined here are only available or visible to classes that are descended from this '''ancestor''' class, and inherit its properties or methods<br />
*'''public''' - this means that items defined here are available to any programming unit that includes the current unit in its [[Glossary#Uses | Uses]] clause <br />
*'''published''' - is the same as a '''public''' section, but the compiler also generates type information that is needed for automatic streaming of these classes. Often the list of published items appear in the Object Inspector of Lazarus; if there is no '''published''' list, all the '''public''' fields usually appear in the Object Inspector.<br />
<br />
=== Methods ===<br />
A method is just like a standard procedure or function, but can have some additional '''directives'''.<br />
<br />
Some of the methods defined above are labelled with the directive '''virtual'''; others are labelled with the '''override''' directive.<br />
*'''virtual''' means that the type or actual instance of a method is not known at compile-time, but is selected at run-time depending on what sub-program actually calls the method. It could be considered a place-holder in the definition of the class.<br />
*'''override''' means that at run-time the locally given definition can take the place of a definition inherited from an ancestor class, particularly if it was '''virtual'''. If you particularly want to use the method defined in the ancestor class, it is sometimes necessary to call it specifically with the '''inherited''' clause.<br />
<br />
Methods with no virtual or override directive are '''static''' methods (the usual kind in Pascal). Those with a virtual or override directive are '''dynamic'''.<br />
<br />
Special instances of methods are:<br />
*'''create''' - a '''constructor''' for a class, which takes care of allocating memory, collecting together all the information needed and configuring/initializing the various properties.<br />
*'''destroy''' - a '''destructor''' for a class, which removes all the parts of the class from the system in an orderly and logical way, and returns all its resources for the system to re-use.<br />
<br />
=== Properties ===<br />
<br />
Properties are just like ordinary fields in a conventional Pascal record, but they can have '''read''' and/or '''write''' specifiers.<br />
*'''read''' specifier is a field, or a function that returns a result of the correct type for the property. In the example above, the property ''Color'' has a read specifier ''FColor'', which is a local variable containing the value to be used. If a property has a '''read''' but no '''write''' specifier, it is read-only.<br />
*'''write''' specifier is a field, or a procedure that will store the value of the property in a specific location. In the example above, ''Color'' has a write specifier ''SetColor'' that is a procedure (defined in the '''protected''' section) for writing the color value to some specified location. If a property has a '''write''' but no '''read''' specifier, it is write-only.<br />
*'''default''' - note that it is possible to set a '''default''' value for a property. For example, ''Color'' here is given the default value ''clBlack'', or black, at the time of creation. It could subsequently be given a different value, by a programming assignment statement, or in the Object Inspector.<br />
<br />
== Further information ==<br />
<br />
This has only scratched the surface of the topic. For more details, readers are strongly recommended to read the [http://lazarus-ccr.sourceforge.net/fpcdoc/ref/ref.html FreePascal] manuals, especially Chapters 5 ('''Objects''') and 6 ('''Classes''')<br />
<br />
--[[User:Kirkpatc|Kirkpatc]] 11:04, 20 July 2008 (CEST)<br />
<br />
----<br />
[[Console Mode Pascal]]</div>Amedeohttps://wiki.freepascal.org/index.php?title=Object_Oriented_Programming_with_Free_Pascal_and_Lazarus/it&diff=34767Object Oriented Programming with Free Pascal and Lazarus/it2009-04-01T09:14:28Z<p>Amedeo: /* Object-Oriented Extensions to standard Pascal */</p>
<hr />
<div>{{Object_Oriented_Programming_with_FreePascal_and_Lazarus}}<br />
<br />
Esistono molte guide eccellenti su Pascal, ma questa guida tenta di coinvolgere ulteriormente il principiante , nella programmazione orientata agli oggetti o [[Glossary#OO | Object-Oriented Programming]], che è un'estensione dello standard pascal, offerta da Turbo pascal, Delphi e FreePascal/Lazarus.<br />
<br />
Un [[Glossary#Object | Object]] è un'estensione della struttura standard pascal detta [http://wiki.lazarus.freepascal.org/Record record]<br />
<br />
La programmazione Pascal in testo standard è adatta alla creazione di applicazioni che, come le applicazioni Unix tradizionali,sono adatte per fare una cosa e per farla molto bene.<br />
<br />
Ciò che un programma fa può essere un'azione veramente complicata ,e può offrire all'utente molte opzioni di menu,<br />
ma è essenzialmente ristretta ad obbedire a comandi che l'utente digita da tastiera e a listare le sue risposte sul terminale o sulla stampante. <br />
<br />
Per poter produrre una [[Glossary#GUI | Graphical User Interface (GUI)]] usualmente si utilizza una sorta di Metodo di programmazione orientata agli oggetti (spesso facendo uso di [[Glossary#C Programming Language | C]] o di una delle sue varianti, o Visual Basic, o una delle [[Glossary#OO | OO]] varianti di Pascal quali [[Glossary#FreePascal | FreePascal]] con o senza [[Glossary#Lazarus | Lazarus]]). <br />
<br />
In una GUI all'utente vengono presentate schermate con un gran numero di immagini organizzate in modo strutturato, consistenti in un'insieme di strumenti o [[Glossary#Widget | Widgets]] che sono associati con varie azioni quali <br />
*selezioni da menu, <br />
*aperture o salvataggio files , <br />
*connessioni ad Internet, <br />
*esecuzioni di calcoli numerici, etc. <br />
<br />
L'utente dovrà muovere il mouse o qualche altro puntatore o strumento sullo schermo, per selezionare le azioni che saranno eseguite in risposta al click del mouse o ai tasti premuti.<br />
<br />
I sistemi per offrire una complessa interfaccia grafica possono essere scritti in Pascal standard o quasi qualsiasi altro linguaggio di programmazione, ma è molto più facile l'utilizzo di un sistema orientato agli oggetti, in cui ogni oggetto grafico sullo schermo può avere tutte le sue proprietà e le sue procedure e funzioni connesse con il suo uso conglobate in una struttura comune.<br />
<br />
<br />
== Oggetti - una analogia con il mondo reale == <br />
Consideriamo le analogie di un campione di sangue prelevato in un ospedale o in uno studio medico.<br />
=== Campione di sangue ===<br />
Il campione fisico è certamente un oggetto o '''object'''; ed ha , associato con esso una quantità di informazioni,documenti ed altri oggetti fisici. <br />
<br />
*'''Provetta''', del tipo determinato dal test che si dovrà eseguire.<br />
<br />
*'''Metodica''' (o ''metodo'', ''procedura operativa standard'') utilizzata dall'infermiera o dal tecnico di laboratorio che prelevano e processano il campione <br />
** che tipo di provetta si dovrà usare, <br />
**come processare il campione<br />
**come conservarlo prima di consegnarlo al laboratorio. <br />
<br />
*'''Etichetta''' sulla provetta con i dettagli per <br />
**identificare il campione <br />
**Nome e cognome e data di nascita del paziente <br />
** data e ora del prelievo <br />
** analisi richieste. <br />
<br />
*'''Modulo di richiesta''' che accompagna il campione per il laboratorio cui il campione è diretto <br />
** ID Campione<br />
**ID del medico richiedente<br />
** quali analisi il medico richiede e <br />
**anamnesi e dettagli completi del paziente<br />
**La possibile diagnosi di cui si richiede conferma. <br />
<br />
<br />
Una copia delle richiesta viene conservata nella cartella clinica per ricordare al medico di attendersi risultati entro un periodo di tempo adeguato. <br />
<br />
<br />
*In laboratorio - '''metodi locali''' per determinare <br />
**come il campione deve essere analizzato, <br />
**Quale strumento usare, <br />
**come lo strumento dovrà operare e come dovrà essere calibrato, <br />
**come il risultato dovrà essere memorizzato formattato e <br />
**presentato al medico. <br />
<br />
L'effettivo'' 'risultato''' è un dato che il medico usa per formulare la diagnosi, e una copia dei risultati è archiviata nella cartella clinica del paziente.<br />
<br />
Il campione fisico può essere conservato per riferimento,per test di conferma o ulteriori test, o potrà essere smaltito in ottemperanza alle norme per lo smaltimento dei campioni biologici o mediante incenerimento, ci sarà un metodo per descrivere questo procedimento.<br />
<br />
<br />
Non è necessario che il medico dica tutti i dettagli operativi e le istruzioni di lavoro ogni qualvolta che un campione viene prelevato; anzi,egli può avere ben poche conoscenze di come il campione verrà processato dal laboratorio. <br />
<br />
I dettagli dei vari processi sono'' '''ereditati''' dai precedenti processi dei campione in analisi ,ossia a priori si è stabilito il metodo di processo del campione - ci sarà un piano generico per l'intera sequenza, e insieme abbiamo potuto pensare al campione di sangue,a tutti i suoi documenti e dati, e la metodica di base, come a un complesso'' 'oggetto'''.<br />
<br />
<br />
<br />
Nella mente del medico, il campione di sangue è visto come un'unica entità, come i suoi risultati, e per gli infermieri e tecnici il campione, la provetta, l'etichetta e le condizioni di conservazione anch'esse sono identificate come se fossero una sola entità.<br />
<br />
Traduzione da completare.....<br />
<br />
=== Un'altro esempio- Automobile ===<br />
Se non vi piace l'esempio del campione di sangue,lo stesso tipo di ragionamento può essere applicato all'automobile consegnata al garage per una riparazione.<br />
Ciò potrebbe consistere in<br />
*Il veicolo fisico<br />
*i documenti in possesso del proprietario: Libretto di circolazione (comprese targhe), le assicurazioni, le ricevute per l'acquisto, i pezzi di ricambio, le riparazioni, ecc<br />
*il consumo di carburante<br />
*i conducenti autorizzati ad utilizzare il veicolo, con le loro patenti di guida<br />
*gli interventi di manutenzione registrati presso il garage<br />
*metodi o procedure da seguire per la verifica e la manutenzione di routine<br />
*metodi da seguire per le riparazioni non di routine, ecc<br />
*informazioni di fatturazione per il cliente<br />
<br />
== Esempi di programmazione ==<br />
<br />
Basta con questa introduzione, fatta di esempi del mondo reale! Dobbiamo procedere con l'obiettivo principale: la programmazione FreePascal<br />
<br />
<br />
<br />
Dobbiamo considerare la creazione di un semplice modulo con pochi controlli per una applicazione in FreePascal / Lazzaro.<br />
<br />
<div class="floatleft">[[Image:ObjectInspector-TForm.png]]</div><br />
<div class="floatright">[[Image:BlankForm.png]]</div><br />
<br />
<br />
Richiamando la IDE di Lazarus, al programmatore viene presentato un modello vuoto "Form" in progettazione, in cui egli dovrà porre oggetti e vari controlli.<br />
<br />
Si noti che il Form vuoto precostituito è già un oggetto, con le proprie caratteristiche, come la posizione (in alto e sinistra), le dimensioni (altezza e larghezza), il colore, il font di default per l'aggiunta di testo ecc<br />
<br />
<br />
<br />
----<br />
<br />
<br />
Se un controllo Button, un tasto, viene immesso sul Form (tipo TButton), questi avrà una serie di proprietà, che possono essere esaminate nella finestra Object Inspector .<br />
<br />
<br />
Molte delle proprietà hanno nomi simili a quelle del Modulo 'Form', questo è dovuto al fatto che molte proprietà sono'' 'ereditate''' da parte di alcuni comuni antenati di classe, che definiscono le proprietà come sono definite e gestite dalle classi discendenti. <br />
<br />
Così come per le proprietà, l'Object Inspector offre una scheda denominata'' 'Eventi''', che dà accesso ai gestori di eventi 'Event Handlers' che sono metodi per gestire tali eventi, come un clic del mouse su un pulsante (OnClick) o alcuni cambiamento di posizione, le dimensioni o altre proprietà (OnChange).<br />
<br />
L'immagine fisica del pulsante nel Modulo o Form, insieme con tutte le sue proprietà e metodi di gestione, dovrebbe essere considerato come una singola entità o'' 'oggetto''' in Pascal.<br />
<br />
<div class="floatleft">[[Image:ObjectInspector-TButton.png]]</div><br />
<div class="floatright">[[Image:FormWithButton.png]]</div><br />
<div class="floatright">[[Image:Source_FormWithButton1.png ]]</div><br />
<br />
== Object-Oriented Extensions to standard Pascal ==<br />
<br />
La struttura Pascal di tipo record viene estesa per definire un<br />
=== Object ===<br />
<br />
Un oggetto è uno speciale tipo di record. Il record contiene tutti i campi che sono dichiarati nella definizione dell'oggetto (proprio come un convenzionale record), ma ora le procedure e le funzioni possono essere dichiarate come se fossero parte del record e si richiamano come puntatori ai metodi associati con il tipo di oggetto.<br />
<br />
Ad esempio, un oggetto può contenere una serie di valori reali, una matrice,unitamente con un metodo di calcolo della media.<br />
<br />
Type<br />
Average = Object<br />
NumVal: Integer;<br />
Values: Array [1..200] of Real;<br />
Function Mean: Real; { calculates the average value of the array }<br />
End;<br />
<br />
Objects can ”inherit” fields and methods from ”parent” objects. This means that these fields and methods can be used as if they were included in the objects declared as a ”child” object.<br />
Gli oggetti possono "ereditare" campi e metodi da oggetti "madre". Ciò significa che questi campi e metodi possono essere usati come se fossero incluse nel oggetti dichiarati come un oggetto figlio.<br />
<br />
Furthermore, a concept of visibility is introduced: fields, procedures and functions can be declared<br />
as public, protected or private. By default, fields and methods are public, and can be exported outside the<br />
current unit. Protected fields or methods are available only to objects descended from the current ancestor object. Fields or methods that are declared private are only accessible in the current unit:<br />
their scope is limited to the implementation of the current unit.<br />
<br />
=== Class ===<br />
Objects are not used very often by themselves in FreePascal and Lazarus; instead, Classes are used very widely. A Class is defined in almost the same way as an Object, but is a pointer to an Object rather than the Object itself. Technically, this means that the Class is allocated on the Heap of a program, whereas the Object is allocated on the Stack.<br />
<br />
Here is a simple example of a typical Class declaration:<br />
{-----------------------------------------}<br />
{example of Class declaration from the LCL}<br />
{-----------------------------------------}<br />
TPen = class(TFPCustomPen)<br />
private<br />
FColor: TColor;<br />
FPenHandleCached: boolean;<br />
FReference: TWSPenReference;<br />
procedure FreeReference;<br />
function GetHandle: HPEN;<br />
function GetReference: TWSPenReference;<br />
procedure ReferenceNeeded;<br />
procedure SetHandle(const Value: HPEN);<br />
protected<br />
procedure DoAllocateResources; override;<br />
procedure DoDeAllocateResources; override;<br />
procedure DoCopyProps(From: TFPCanvasHelper); override;<br />
procedure SetColor<br />
(const NewColor: TColor; const NewFPColor: TFPColor); virtual;<br />
procedure SetFPColor(const AValue: TFPColor); override;<br />
procedure SetColor(Value: TColor);<br />
procedure SetMode(Value: TPenMode); override;<br />
procedure SetStyle(Value: TPenStyle); override;<br />
procedure SetWidth(value: Integer); override;<br />
public<br />
constructor Create; override;<br />
destructor Destroy; override;<br />
procedure Assign(Source: TPersistent); override;<br />
property Handle: HPEN read GetHandle write SetHandle; deprecated;<br />
property Reference: TWSPenReference read GetReference;<br />
published<br />
property Color: TColor read FColor write SetColor default clBlack;<br />
property Mode default pmCopy;<br />
property Style default psSolid;<br />
property Width default 1;<br />
end;<br />
<br />
<br />
Note that this class is defined as an instance of another '''parent''' or '''ancestor''' class (''TFPCustomPen'') from which it '''inherits''' all its properties and methods. It has some fields of its own, grouped under<br />
*'''private''' - this means that items defined here are only available or visible to other classes or procedures/function defined within the same program unit (this example is from ''Graphics'', so any of the other classes such as ''TBitMap'', ''TPicture'' etc in the same unit can use them). They are essentially local variables (eg ''FColor'', ''FPenHandleCached'') or locally used methods (''GetHandle'', ''SetHandle'') but can be used or referred to in items declared in the '''protected''' or '''public''' sections.<br />
*'''protected''' - this means that items defined here are only available or visible to classes that are descended from this '''ancestor''' class, and inherit its properties or methods<br />
*'''public''' - this means that items defined here are available to any programming unit that includes the current unit in its [[Glossary#Uses | Uses]] clause <br />
*'''published''' - is the same as a '''public''' section, but the compiler also generates type information that is needed for automatic streaming of these classes. Often the list of published items appear in the Object Inspector of Lazarus; if there is no '''published''' list, all the '''public''' fields usually appear in the Object Inspector.<br />
<br />
=== Methods ===<br />
A method is just like a standard procedure or function, but can have some additional '''directives'''.<br />
<br />
Some of the methods defined above are labelled with the directive '''virtual'''; others are labelled with the '''override''' directive.<br />
*'''virtual''' means that the type or actual instance of a method is not known at compile-time, but is selected at run-time depending on what sub-program actually calls the method. It could be considered a place-holder in the definition of the class.<br />
*'''override''' means that at run-time the locally given definition can take the place of a definition inherited from an ancestor class, particularly if it was '''virtual'''. If you particularly want to use the method defined in the ancestor class, it is sometimes necessary to call it specifically with the '''inherited''' clause.<br />
<br />
Methods with no virtual or override directive are '''static''' methods (the usual kind in Pascal). Those with a virtual or override directive are '''dynamic'''.<br />
<br />
Special instances of methods are:<br />
*'''create''' - a '''constructor''' for a class, which takes care of allocating memory, collecting together all the information needed and configuring/initializing the various properties.<br />
*'''destroy''' - a '''destructor''' for a class, which removes all the parts of the class from the system in an orderly and logical way, and returns all its resources for the system to re-use.<br />
<br />
=== Properties ===<br />
<br />
Properties are just like ordinary fields in a conventional Pascal record, but they can have '''read''' and/or '''write''' specifiers.<br />
*'''read''' specifier is a field, or a function that returns a result of the correct type for the property. In the example above, the property ''Color'' has a read specifier ''FColor'', which is a local variable containing the value to be used. If a property has a '''read''' but no '''write''' specifier, it is read-only.<br />
*'''write''' specifier is a field, or a procedure that will store the value of the property in a specific location. In the example above, ''Color'' has a write specifier ''SetColor'' that is a procedure (defined in the '''protected''' section) for writing the color value to some specified location. If a property has a '''write''' but no '''read''' specifier, it is write-only.<br />
*'''default''' - note that it is possible to set a '''default''' value for a property. For example, ''Color'' here is given the default value ''clBlack'', or black, at the time of creation. It could subsequently be given a different value, by a programming assignment statement, or in the Object Inspector.<br />
<br />
== Further information ==<br />
<br />
This has only scratched the surface of the topic. For more details, readers are strongly recommended to read the [http://lazarus-ccr.sourceforge.net/fpcdoc/ref/ref.html FreePascal] manuals, especially Chapters 5 ('''Objects''') and 6 ('''Classes''')<br />
<br />
--[[User:Kirkpatc|Kirkpatc]] 11:04, 20 July 2008 (CEST)<br />
<br />
----<br />
[[Console Mode Pascal]]</div>Amedeohttps://wiki.freepascal.org/index.php?title=Object_Oriented_Programming_with_Free_Pascal_and_Lazarus/it&diff=34765Object Oriented Programming with Free Pascal and Lazarus/it2009-04-01T08:47:06Z<p>Amedeo: /* Esempi di programmazione */</p>
<hr />
<div>{{Object_Oriented_Programming_with_FreePascal_and_Lazarus}}<br />
<br />
Esistono molte guide eccellenti su Pascal, ma questa guida tenta di coinvolgere ulteriormente il principiante , nella programmazione orientata agli oggetti o [[Glossary#OO | Object-Oriented Programming]], che è un'estensione dello standard pascal, offerta da Turbo pascal, Delphi e FreePascal/Lazarus.<br />
<br />
Un [[Glossary#Object | Object]] è un'estensione della struttura standard pascal detta [http://wiki.lazarus.freepascal.org/Record record]<br />
<br />
La programmazione Pascal in testo standard è adatta alla creazione di applicazioni che, come le applicazioni Unix tradizionali,sono adatte per fare una cosa e per farla molto bene.<br />
<br />
Ciò che un programma fa può essere un'azione veramente complicata ,e può offrire all'utente molte opzioni di menu,<br />
ma è essenzialmente ristretta ad obbedire a comandi che l'utente digita da tastiera e a listare le sue risposte sul terminale o sulla stampante. <br />
<br />
Per poter produrre una [[Glossary#GUI | Graphical User Interface (GUI)]] usualmente si utilizza una sorta di Metodo di programmazione orientata agli oggetti (spesso facendo uso di [[Glossary#C Programming Language | C]] o di una delle sue varianti, o Visual Basic, o una delle [[Glossary#OO | OO]] varianti di Pascal quali [[Glossary#FreePascal | FreePascal]] con o senza [[Glossary#Lazarus | Lazarus]]). <br />
<br />
In una GUI all'utente vengono presentate schermate con un gran numero di immagini organizzate in modo strutturato, consistenti in un'insieme di strumenti o [[Glossary#Widget | Widgets]] che sono associati con varie azioni quali <br />
*selezioni da menu, <br />
*aperture o salvataggio files , <br />
*connessioni ad Internet, <br />
*esecuzioni di calcoli numerici, etc. <br />
<br />
L'utente dovrà muovere il mouse o qualche altro puntatore o strumento sullo schermo, per selezionare le azioni che saranno eseguite in risposta al click del mouse o ai tasti premuti.<br />
<br />
I sistemi per offrire una complessa interfaccia grafica possono essere scritti in Pascal standard o quasi qualsiasi altro linguaggio di programmazione, ma è molto più facile l'utilizzo di un sistema orientato agli oggetti, in cui ogni oggetto grafico sullo schermo può avere tutte le sue proprietà e le sue procedure e funzioni connesse con il suo uso conglobate in una struttura comune.<br />
<br />
<br />
== Oggetti - una analogia con il mondo reale == <br />
Consideriamo le analogie di un campione di sangue prelevato in un ospedale o in uno studio medico.<br />
=== Campione di sangue ===<br />
Il campione fisico è certamente un oggetto o '''object'''; ed ha , associato con esso una quantità di informazioni,documenti ed altri oggetti fisici. <br />
<br />
*'''Provetta''', del tipo determinato dal test che si dovrà eseguire.<br />
<br />
*'''Metodica''' (o ''metodo'', ''procedura operativa standard'') utilizzata dall'infermiera o dal tecnico di laboratorio che prelevano e processano il campione <br />
** che tipo di provetta si dovrà usare, <br />
**come processare il campione<br />
**come conservarlo prima di consegnarlo al laboratorio. <br />
<br />
*'''Etichetta''' sulla provetta con i dettagli per <br />
**identificare il campione <br />
**Nome e cognome e data di nascita del paziente <br />
** data e ora del prelievo <br />
** analisi richieste. <br />
<br />
*'''Modulo di richiesta''' che accompagna il campione per il laboratorio cui il campione è diretto <br />
** ID Campione<br />
**ID del medico richiedente<br />
** quali analisi il medico richiede e <br />
**anamnesi e dettagli completi del paziente<br />
**La possibile diagnosi di cui si richiede conferma. <br />
<br />
<br />
Una copia delle richiesta viene conservata nella cartella clinica per ricordare al medico di attendersi risultati entro un periodo di tempo adeguato. <br />
<br />
<br />
*In laboratorio - '''metodi locali''' per determinare <br />
**come il campione deve essere analizzato, <br />
**Quale strumento usare, <br />
**come lo strumento dovrà operare e come dovrà essere calibrato, <br />
**come il risultato dovrà essere memorizzato formattato e <br />
**presentato al medico. <br />
<br />
L'effettivo'' 'risultato''' è un dato che il medico usa per formulare la diagnosi, e una copia dei risultati è archiviata nella cartella clinica del paziente.<br />
<br />
Il campione fisico può essere conservato per riferimento,per test di conferma o ulteriori test, o potrà essere smaltito in ottemperanza alle norme per lo smaltimento dei campioni biologici o mediante incenerimento, ci sarà un metodo per descrivere questo procedimento.<br />
<br />
<br />
Non è necessario che il medico dica tutti i dettagli operativi e le istruzioni di lavoro ogni qualvolta che un campione viene prelevato; anzi,egli può avere ben poche conoscenze di come il campione verrà processato dal laboratorio. <br />
<br />
I dettagli dei vari processi sono'' '''ereditati''' dai precedenti processi dei campione in analisi ,ossia a priori si è stabilito il metodo di processo del campione - ci sarà un piano generico per l'intera sequenza, e insieme abbiamo potuto pensare al campione di sangue,a tutti i suoi documenti e dati, e la metodica di base, come a un complesso'' 'oggetto'''.<br />
<br />
<br />
<br />
Nella mente del medico, il campione di sangue è visto come un'unica entità, come i suoi risultati, e per gli infermieri e tecnici il campione, la provetta, l'etichetta e le condizioni di conservazione anch'esse sono identificate come se fossero una sola entità.<br />
<br />
Traduzione da completare.....<br />
<br />
=== Un'altro esempio- Automobile ===<br />
Se non vi piace l'esempio del campione di sangue,lo stesso tipo di ragionamento può essere applicato all'automobile consegnata al garage per una riparazione.<br />
Ciò potrebbe consistere in<br />
*Il veicolo fisico<br />
*i documenti in possesso del proprietario: Libretto di circolazione (comprese targhe), le assicurazioni, le ricevute per l'acquisto, i pezzi di ricambio, le riparazioni, ecc<br />
*il consumo di carburante<br />
*i conducenti autorizzati ad utilizzare il veicolo, con le loro patenti di guida<br />
*gli interventi di manutenzione registrati presso il garage<br />
*metodi o procedure da seguire per la verifica e la manutenzione di routine<br />
*metodi da seguire per le riparazioni non di routine, ecc<br />
*informazioni di fatturazione per il cliente<br />
<br />
== Esempi di programmazione ==<br />
<br />
Basta con questa introduzione, fatta di esempi del mondo reale! Dobbiamo procedere con l'obiettivo principale: la programmazione FreePascal<br />
<br />
<br />
<br />
Dobbiamo considerare la creazione di un semplice modulo con pochi controlli per una applicazione in FreePascal / Lazzaro.<br />
<br />
<div class="floatleft">[[Image:ObjectInspector-TForm.png]]</div><br />
<div class="floatright">[[Image:BlankForm.png]]</div><br />
<br />
<br />
Richiamando la IDE di Lazarus, al programmatore viene presentato un modello vuoto "Form" in progettazione, in cui egli dovrà porre oggetti e vari controlli.<br />
<br />
Si noti che il Form vuoto precostituito è già un oggetto, con le proprie caratteristiche, come la posizione (in alto e sinistra), le dimensioni (altezza e larghezza), il colore, il font di default per l'aggiunta di testo ecc<br />
<br />
<br />
<br />
----<br />
<br />
<br />
Se un controllo Button, un tasto, viene immesso sul Form (tipo TButton), questi avrà una serie di proprietà, che possono essere esaminate nella finestra Object Inspector .<br />
<br />
<br />
Molte delle proprietà hanno nomi simili a quelle del Modulo 'Form', questo è dovuto al fatto che molte proprietà sono'' 'ereditate''' da parte di alcuni comuni antenati di classe, che definiscono le proprietà come sono definite e gestite dalle classi discendenti. <br />
<br />
Così come per le proprietà, l'Object Inspector offre una scheda denominata'' 'Eventi''', che dà accesso ai gestori di eventi 'Event Handlers' che sono metodi per gestire tali eventi, come un clic del mouse su un pulsante (OnClick) o alcuni cambiamento di posizione, le dimensioni o altre proprietà (OnChange).<br />
<br />
L'immagine fisica del pulsante nel Modulo o Form, insieme con tutte le sue proprietà e metodi di gestione, dovrebbe essere considerato come una singola entità o'' 'oggetto''' in Pascal.<br />
<br />
<div class="floatleft">[[Image:ObjectInspector-TButton.png]]</div><br />
<div class="floatright">[[Image:FormWithButton.png]]</div><br />
<div class="floatright">[[Image:Source_FormWithButton1.png ]]</div><br />
<br />
== Object-Oriented Extensions to standard Pascal ==<br />
<br />
The Pascal record structure is extended by defining an <br />
=== Object ===<br />
<br />
An Object is a special kind of record. The record contains all the fields that<br />
are declared in the object's definition (just like a conventional record), but now procedures and functions can be declared as if they were part of the record and are held as pointers to the methods associated with the object's type. <br />
<br />
For example, an object could contain an array of real values, together with a Method for calculating the average.<br />
<br />
Type<br />
Average = Object<br />
NumVal: Integer;<br />
Values: Array [1..200] of Real;<br />
Function Mean: Real; { calculates the average value of the array }<br />
End;<br />
<br />
Objects can ”inherit” fields and methods from ”parent” objects. This means that these fields and methods can be used as if they were included in the objects declared as a ”child” object.<br />
<br />
Furthermore, a concept of visibility is introduced: fields, procedures and functions can be declared<br />
as public, protected or private. By default, fields and methods are public, and can be exported outside the<br />
current unit. Protected fields or methods are available only to objects descended from the current ancestor object. Fields or methods that are declared private are only accessible in the current unit:<br />
their scope is limited to the implementation of the current unit.<br />
<br />
=== Class ===<br />
Objects are not used very often by themselves in FreePascal and Lazarus; instead, Classes are used very widely. A Class is defined in almost the same way as an Object, but is a pointer to an Object rather than the Object itself. Technically, this means that the Class is allocated on the Heap of a program, whereas the Object is allocated on the Stack.<br />
<br />
Here is a simple example of a typical Class declaration:<br />
{-----------------------------------------}<br />
{example of Class declaration from the LCL}<br />
{-----------------------------------------}<br />
TPen = class(TFPCustomPen)<br />
private<br />
FColor: TColor;<br />
FPenHandleCached: boolean;<br />
FReference: TWSPenReference;<br />
procedure FreeReference;<br />
function GetHandle: HPEN;<br />
function GetReference: TWSPenReference;<br />
procedure ReferenceNeeded;<br />
procedure SetHandle(const Value: HPEN);<br />
protected<br />
procedure DoAllocateResources; override;<br />
procedure DoDeAllocateResources; override;<br />
procedure DoCopyProps(From: TFPCanvasHelper); override;<br />
procedure SetColor<br />
(const NewColor: TColor; const NewFPColor: TFPColor); virtual;<br />
procedure SetFPColor(const AValue: TFPColor); override;<br />
procedure SetColor(Value: TColor);<br />
procedure SetMode(Value: TPenMode); override;<br />
procedure SetStyle(Value: TPenStyle); override;<br />
procedure SetWidth(value: Integer); override;<br />
public<br />
constructor Create; override;<br />
destructor Destroy; override;<br />
procedure Assign(Source: TPersistent); override;<br />
property Handle: HPEN read GetHandle write SetHandle; deprecated;<br />
property Reference: TWSPenReference read GetReference;<br />
published<br />
property Color: TColor read FColor write SetColor default clBlack;<br />
property Mode default pmCopy;<br />
property Style default psSolid;<br />
property Width default 1;<br />
end;<br />
<br />
<br />
Note that this class is defined as an instance of another '''parent''' or '''ancestor''' class (''TFPCustomPen'') from which it '''inherits''' all its properties and methods. It has some fields of its own, grouped under<br />
*'''private''' - this means that items defined here are only available or visible to other classes or procedures/function defined within the same program unit (this example is from ''Graphics'', so any of the other classes such as ''TBitMap'', ''TPicture'' etc in the same unit can use them). They are essentially local variables (eg ''FColor'', ''FPenHandleCached'') or locally used methods (''GetHandle'', ''SetHandle'') but can be used or referred to in items declared in the '''protected''' or '''public''' sections.<br />
*'''protected''' - this means that items defined here are only available or visible to classes that are descended from this '''ancestor''' class, and inherit its properties or methods<br />
*'''public''' - this means that items defined here are available to any programming unit that includes the current unit in its [[Glossary#Uses | Uses]] clause <br />
*'''published''' - is the same as a '''public''' section, but the compiler also generates type information that is needed for automatic streaming of these classes. Often the list of published items appear in the Object Inspector of Lazarus; if there is no '''published''' list, all the '''public''' fields usually appear in the Object Inspector.<br />
<br />
=== Methods ===<br />
A method is just like a standard procedure or function, but can have some additional '''directives'''.<br />
<br />
Some of the methods defined above are labelled with the directive '''virtual'''; others are labelled with the '''override''' directive.<br />
*'''virtual''' means that the type or actual instance of a method is not known at compile-time, but is selected at run-time depending on what sub-program actually calls the method. It could be considered a place-holder in the definition of the class.<br />
*'''override''' means that at run-time the locally given definition can take the place of a definition inherited from an ancestor class, particularly if it was '''virtual'''. If you particularly want to use the method defined in the ancestor class, it is sometimes necessary to call it specifically with the '''inherited''' clause.<br />
<br />
Methods with no virtual or override directive are '''static''' methods (the usual kind in Pascal). Those with a virtual or override directive are '''dynamic'''.<br />
<br />
Special instances of methods are:<br />
*'''create''' - a '''constructor''' for a class, which takes care of allocating memory, collecting together all the information needed and configuring/initializing the various properties.<br />
*'''destroy''' - a '''destructor''' for a class, which removes all the parts of the class from the system in an orderly and logical way, and returns all its resources for the system to re-use.<br />
<br />
=== Properties ===<br />
<br />
Properties are just like ordinary fields in a conventional Pascal record, but they can have '''read''' and/or '''write''' specifiers.<br />
*'''read''' specifier is a field, or a function that returns a result of the correct type for the property. In the example above, the property ''Color'' has a read specifier ''FColor'', which is a local variable containing the value to be used. If a property has a '''read''' but no '''write''' specifier, it is read-only.<br />
*'''write''' specifier is a field, or a procedure that will store the value of the property in a specific location. In the example above, ''Color'' has a write specifier ''SetColor'' that is a procedure (defined in the '''protected''' section) for writing the color value to some specified location. If a property has a '''write''' but no '''read''' specifier, it is write-only.<br />
*'''default''' - note that it is possible to set a '''default''' value for a property. For example, ''Color'' here is given the default value ''clBlack'', or black, at the time of creation. It could subsequently be given a different value, by a programming assignment statement, or in the Object Inspector.<br />
<br />
<br />
== Further information ==<br />
<br />
This has only scratched the surface of the topic. For more details, readers are strongly recommended to read the [http://lazarus-ccr.sourceforge.net/fpcdoc/ref/ref.html FreePascal] manuals, especially Chapters 5 ('''Objects''') and 6 ('''Classes''')<br />
<br />
--[[User:Kirkpatc|Kirkpatc]] 11:04, 20 July 2008 (CEST)<br />
<br />
----<br />
[[Console Mode Pascal]]</div>Amedeohttps://wiki.freepascal.org/index.php?title=Object_Oriented_Programming_with_Free_Pascal_and_Lazarus/it&diff=34764Object Oriented Programming with Free Pascal and Lazarus/it2009-04-01T08:39:44Z<p>Amedeo: /* Esempi di programmazione */</p>
<hr />
<div>{{Object_Oriented_Programming_with_FreePascal_and_Lazarus}}<br />
<br />
Esistono molte guide eccellenti su Pascal, ma questa guida tenta di coinvolgere ulteriormente il principiante , nella programmazione orientata agli oggetti o [[Glossary#OO | Object-Oriented Programming]], che è un'estensione dello standard pascal, offerta da Turbo pascal, Delphi e FreePascal/Lazarus.<br />
<br />
Un [[Glossary#Object | Object]] è un'estensione della struttura standard pascal detta [http://wiki.lazarus.freepascal.org/Record record]<br />
<br />
La programmazione Pascal in testo standard è adatta alla creazione di applicazioni che, come le applicazioni Unix tradizionali,sono adatte per fare una cosa e per farla molto bene.<br />
<br />
Ciò che un programma fa può essere un'azione veramente complicata ,e può offrire all'utente molte opzioni di menu,<br />
ma è essenzialmente ristretta ad obbedire a comandi che l'utente digita da tastiera e a listare le sue risposte sul terminale o sulla stampante. <br />
<br />
Per poter produrre una [[Glossary#GUI | Graphical User Interface (GUI)]] usualmente si utilizza una sorta di Metodo di programmazione orientata agli oggetti (spesso facendo uso di [[Glossary#C Programming Language | C]] o di una delle sue varianti, o Visual Basic, o una delle [[Glossary#OO | OO]] varianti di Pascal quali [[Glossary#FreePascal | FreePascal]] con o senza [[Glossary#Lazarus | Lazarus]]). <br />
<br />
In una GUI all'utente vengono presentate schermate con un gran numero di immagini organizzate in modo strutturato, consistenti in un'insieme di strumenti o [[Glossary#Widget | Widgets]] che sono associati con varie azioni quali <br />
*selezioni da menu, <br />
*aperture o salvataggio files , <br />
*connessioni ad Internet, <br />
*esecuzioni di calcoli numerici, etc. <br />
<br />
L'utente dovrà muovere il mouse o qualche altro puntatore o strumento sullo schermo, per selezionare le azioni che saranno eseguite in risposta al click del mouse o ai tasti premuti.<br />
<br />
I sistemi per offrire una complessa interfaccia grafica possono essere scritti in Pascal standard o quasi qualsiasi altro linguaggio di programmazione, ma è molto più facile l'utilizzo di un sistema orientato agli oggetti, in cui ogni oggetto grafico sullo schermo può avere tutte le sue proprietà e le sue procedure e funzioni connesse con il suo uso conglobate in una struttura comune.<br />
<br />
<br />
== Oggetti - una analogia con il mondo reale == <br />
Consideriamo le analogie di un campione di sangue prelevato in un ospedale o in uno studio medico.<br />
=== Campione di sangue ===<br />
Il campione fisico è certamente un oggetto o '''object'''; ed ha , associato con esso una quantità di informazioni,documenti ed altri oggetti fisici. <br />
<br />
*'''Provetta''', del tipo determinato dal test che si dovrà eseguire.<br />
<br />
*'''Metodica''' (o ''metodo'', ''procedura operativa standard'') utilizzata dall'infermiera o dal tecnico di laboratorio che prelevano e processano il campione <br />
** che tipo di provetta si dovrà usare, <br />
**come processare il campione<br />
**come conservarlo prima di consegnarlo al laboratorio. <br />
<br />
*'''Etichetta''' sulla provetta con i dettagli per <br />
**identificare il campione <br />
**Nome e cognome e data di nascita del paziente <br />
** data e ora del prelievo <br />
** analisi richieste. <br />
<br />
*'''Modulo di richiesta''' che accompagna il campione per il laboratorio cui il campione è diretto <br />
** ID Campione<br />
**ID del medico richiedente<br />
** quali analisi il medico richiede e <br />
**anamnesi e dettagli completi del paziente<br />
**La possibile diagnosi di cui si richiede conferma. <br />
<br />
<br />
Una copia delle richiesta viene conservata nella cartella clinica per ricordare al medico di attendersi risultati entro un periodo di tempo adeguato. <br />
<br />
<br />
*In laboratorio - '''metodi locali''' per determinare <br />
**come il campione deve essere analizzato, <br />
**Quale strumento usare, <br />
**come lo strumento dovrà operare e come dovrà essere calibrato, <br />
**come il risultato dovrà essere memorizzato formattato e <br />
**presentato al medico. <br />
<br />
L'effettivo'' 'risultato''' è un dato che il medico usa per formulare la diagnosi, e una copia dei risultati è archiviata nella cartella clinica del paziente.<br />
<br />
Il campione fisico può essere conservato per riferimento,per test di conferma o ulteriori test, o potrà essere smaltito in ottemperanza alle norme per lo smaltimento dei campioni biologici o mediante incenerimento, ci sarà un metodo per descrivere questo procedimento.<br />
<br />
<br />
Non è necessario che il medico dica tutti i dettagli operativi e le istruzioni di lavoro ogni qualvolta che un campione viene prelevato; anzi,egli può avere ben poche conoscenze di come il campione verrà processato dal laboratorio. <br />
<br />
I dettagli dei vari processi sono'' '''ereditati''' dai precedenti processi dei campione in analisi ,ossia a priori si è stabilito il metodo di processo del campione - ci sarà un piano generico per l'intera sequenza, e insieme abbiamo potuto pensare al campione di sangue,a tutti i suoi documenti e dati, e la metodica di base, come a un complesso'' 'oggetto'''.<br />
<br />
<br />
<br />
Nella mente del medico, il campione di sangue è visto come un'unica entità, come i suoi risultati, e per gli infermieri e tecnici il campione, la provetta, l'etichetta e le condizioni di conservazione anch'esse sono identificate come se fossero una sola entità.<br />
<br />
Traduzione da completare.....<br />
<br />
=== Un'altro esempio- Automobile ===<br />
Se non vi piace l'esempio del campione di sangue,lo stesso tipo di ragionamento può essere applicato all'automobile consegnata al garage per una riparazione.<br />
Ciò potrebbe consistere in<br />
*Il veicolo fisico<br />
*i documenti in possesso del proprietario: Libretto di circolazione (comprese targhe), le assicurazioni, le ricevute per l'acquisto, i pezzi di ricambio, le riparazioni, ecc<br />
*il consumo di carburante<br />
*i conducenti autorizzati ad utilizzare il veicolo, con le loro patenti di guida<br />
*gli interventi di manutenzione registrati presso il garage<br />
*metodi o procedure da seguire per la verifica e la manutenzione di routine<br />
*metodi da seguire per le riparazioni non di routine, ecc<br />
*informazioni di fatturazione per il cliente<br />
<br />
== Esempi di programmazione ==<br />
<br />
Basta con questa introduzione, fatta di esempi del mondo reale! Dobbiamo procedere con l'obiettivo principale: la programmazione FreePascal<br />
<br />
<br />
<br />
Dobbiamo considerare la creazione di un semplice modulo con pochi controlli per una applicazione in FreePascal / Lazzaro.<br />
<br />
<div class="floatleft">[[Image:ObjectInspector-TForm.png]]</div><br />
<div class="floatright">[[Image:BlankForm.png]]</div><br />
<br />
<br />
Richiamando la IDE di Lazarus, al programmatore viene presentato un modello vuoto "Form" in progettazione, in cui egli dovrà porre oggetti e vari controlli.<br />
<br />
Si noti che il Form vuoto precostituito è già un oggetto, con le proprie caratteristiche, come la posizione (in alto e sinistra), le dimensioni (altezza e larghezza), il colore, il font di default per l'aggiunta di testo ecc<br />
<br />
<br />
<br />
----<br />
<br />
<br />
Se un controllo Button, un tasto, viene immesso sul Form (tipo TButton), questi avrà una serie di proprietà, che possono essere esaminate nella finestra Object Inspector .<br />
<br />
<br />
Molte delle proprietà hanno nomi simili a quelle del Modulo 'Form', questo è dovuto al fatto che molte proprietà sono'' 'ereditate''' da parte di alcuni comuni antenati di classe, che definisce le proprietà come sono definite e gestite dalle classi discendent. <br />
<br />
As well as properties, the Object Inspector offers a tab called '''Events''', which gives access to Event Handlers which are methods instructing the application how to deal with things such as a mouse click on a button (OnClick) or some change in the position, size or other properties (OnChange).<br />
<br />
The physical image of the Button on the Form, together with all its properties and Event Handler methods, should be regarded as a single entity or '''Object''' in Pascal.<br />
<br />
<div class="floatleft">[[Image:ObjectInspector-TButton.png]]</div><br />
<div class="floatright">[[Image:FormWithButton.png]]</div><br />
<div class="floatright">[[Image:Source_FormWithButton1.png ]]</div><br />
<br />
== Object-Oriented Extensions to standard Pascal ==<br />
<br />
The Pascal record structure is extended by defining an <br />
=== Object ===<br />
<br />
An Object is a special kind of record. The record contains all the fields that<br />
are declared in the object's definition (just like a conventional record), but now procedures and functions can be declared as if they were part of the record and are held as pointers to the methods associated with the object's type. <br />
<br />
For example, an object could contain an array of real values, together with a Method for calculating the average.<br />
<br />
Type<br />
Average = Object<br />
NumVal: Integer;<br />
Values: Array [1..200] of Real;<br />
Function Mean: Real; { calculates the average value of the array }<br />
End;<br />
<br />
Objects can ”inherit” fields and methods from ”parent” objects. This means that these fields and methods can be used as if they were included in the objects declared as a ”child” object.<br />
<br />
Furthermore, a concept of visibility is introduced: fields, procedures and functions can be declared<br />
as public, protected or private. By default, fields and methods are public, and can be exported outside the<br />
current unit. Protected fields or methods are available only to objects descended from the current ancestor object. Fields or methods that are declared private are only accessible in the current unit:<br />
their scope is limited to the implementation of the current unit.<br />
<br />
=== Class ===<br />
Objects are not used very often by themselves in FreePascal and Lazarus; instead, Classes are used very widely. A Class is defined in almost the same way as an Object, but is a pointer to an Object rather than the Object itself. Technically, this means that the Class is allocated on the Heap of a program, whereas the Object is allocated on the Stack.<br />
<br />
Here is a simple example of a typical Class declaration:<br />
{-----------------------------------------}<br />
{example of Class declaration from the LCL}<br />
{-----------------------------------------}<br />
TPen = class(TFPCustomPen)<br />
private<br />
FColor: TColor;<br />
FPenHandleCached: boolean;<br />
FReference: TWSPenReference;<br />
procedure FreeReference;<br />
function GetHandle: HPEN;<br />
function GetReference: TWSPenReference;<br />
procedure ReferenceNeeded;<br />
procedure SetHandle(const Value: HPEN);<br />
protected<br />
procedure DoAllocateResources; override;<br />
procedure DoDeAllocateResources; override;<br />
procedure DoCopyProps(From: TFPCanvasHelper); override;<br />
procedure SetColor<br />
(const NewColor: TColor; const NewFPColor: TFPColor); virtual;<br />
procedure SetFPColor(const AValue: TFPColor); override;<br />
procedure SetColor(Value: TColor);<br />
procedure SetMode(Value: TPenMode); override;<br />
procedure SetStyle(Value: TPenStyle); override;<br />
procedure SetWidth(value: Integer); override;<br />
public<br />
constructor Create; override;<br />
destructor Destroy; override;<br />
procedure Assign(Source: TPersistent); override;<br />
property Handle: HPEN read GetHandle write SetHandle; deprecated;<br />
property Reference: TWSPenReference read GetReference;<br />
published<br />
property Color: TColor read FColor write SetColor default clBlack;<br />
property Mode default pmCopy;<br />
property Style default psSolid;<br />
property Width default 1;<br />
end;<br />
<br />
<br />
Note that this class is defined as an instance of another '''parent''' or '''ancestor''' class (''TFPCustomPen'') from which it '''inherits''' all its properties and methods. It has some fields of its own, grouped under<br />
*'''private''' - this means that items defined here are only available or visible to other classes or procedures/function defined within the same program unit (this example is from ''Graphics'', so any of the other classes such as ''TBitMap'', ''TPicture'' etc in the same unit can use them). They are essentially local variables (eg ''FColor'', ''FPenHandleCached'') or locally used methods (''GetHandle'', ''SetHandle'') but can be used or referred to in items declared in the '''protected''' or '''public''' sections.<br />
*'''protected''' - this means that items defined here are only available or visible to classes that are descended from this '''ancestor''' class, and inherit its properties or methods<br />
*'''public''' - this means that items defined here are available to any programming unit that includes the current unit in its [[Glossary#Uses | Uses]] clause <br />
*'''published''' - is the same as a '''public''' section, but the compiler also generates type information that is needed for automatic streaming of these classes. Often the list of published items appear in the Object Inspector of Lazarus; if there is no '''published''' list, all the '''public''' fields usually appear in the Object Inspector.<br />
<br />
=== Methods ===<br />
A method is just like a standard procedure or function, but can have some additional '''directives'''.<br />
<br />
Some of the methods defined above are labelled with the directive '''virtual'''; others are labelled with the '''override''' directive.<br />
*'''virtual''' means that the type or actual instance of a method is not known at compile-time, but is selected at run-time depending on what sub-program actually calls the method. It could be considered a place-holder in the definition of the class.<br />
*'''override''' means that at run-time the locally given definition can take the place of a definition inherited from an ancestor class, particularly if it was '''virtual'''. If you particularly want to use the method defined in the ancestor class, it is sometimes necessary to call it specifically with the '''inherited''' clause.<br />
<br />
Methods with no virtual or override directive are '''static''' methods (the usual kind in Pascal). Those with a virtual or override directive are '''dynamic'''.<br />
<br />
Special instances of methods are:<br />
*'''create''' - a '''constructor''' for a class, which takes care of allocating memory, collecting together all the information needed and configuring/initializing the various properties.<br />
*'''destroy''' - a '''destructor''' for a class, which removes all the parts of the class from the system in an orderly and logical way, and returns all its resources for the system to re-use.<br />
<br />
=== Properties ===<br />
<br />
Properties are just like ordinary fields in a conventional Pascal record, but they can have '''read''' and/or '''write''' specifiers.<br />
*'''read''' specifier is a field, or a function that returns a result of the correct type for the property. In the example above, the property ''Color'' has a read specifier ''FColor'', which is a local variable containing the value to be used. If a property has a '''read''' but no '''write''' specifier, it is read-only.<br />
*'''write''' specifier is a field, or a procedure that will store the value of the property in a specific location. In the example above, ''Color'' has a write specifier ''SetColor'' that is a procedure (defined in the '''protected''' section) for writing the color value to some specified location. If a property has a '''write''' but no '''read''' specifier, it is write-only.<br />
*'''default''' - note that it is possible to set a '''default''' value for a property. For example, ''Color'' here is given the default value ''clBlack'', or black, at the time of creation. It could subsequently be given a different value, by a programming assignment statement, or in the Object Inspector.<br />
<br />
<br />
== Further information ==<br />
<br />
This has only scratched the surface of the topic. For more details, readers are strongly recommended to read the [http://lazarus-ccr.sourceforge.net/fpcdoc/ref/ref.html FreePascal] manuals, especially Chapters 5 ('''Objects''') and 6 ('''Classes''')<br />
<br />
--[[User:Kirkpatc|Kirkpatc]] 11:04, 20 July 2008 (CEST)<br />
<br />
----<br />
[[Console Mode Pascal]]</div>Amedeohttps://wiki.freepascal.org/index.php?title=Object_Oriented_Programming_with_Free_Pascal_and_Lazarus/it&diff=34763Object Oriented Programming with Free Pascal and Lazarus/it2009-04-01T08:34:48Z<p>Amedeo: /* Esempi di programmazione */</p>
<hr />
<div>{{Object_Oriented_Programming_with_FreePascal_and_Lazarus}}<br />
<br />
Esistono molte guide eccellenti su Pascal, ma questa guida tenta di coinvolgere ulteriormente il principiante , nella programmazione orientata agli oggetti o [[Glossary#OO | Object-Oriented Programming]], che è un'estensione dello standard pascal, offerta da Turbo pascal, Delphi e FreePascal/Lazarus.<br />
<br />
Un [[Glossary#Object | Object]] è un'estensione della struttura standard pascal detta [http://wiki.lazarus.freepascal.org/Record record]<br />
<br />
La programmazione Pascal in testo standard è adatta alla creazione di applicazioni che, come le applicazioni Unix tradizionali,sono adatte per fare una cosa e per farla molto bene.<br />
<br />
Ciò che un programma fa può essere un'azione veramente complicata ,e può offrire all'utente molte opzioni di menu,<br />
ma è essenzialmente ristretta ad obbedire a comandi che l'utente digita da tastiera e a listare le sue risposte sul terminale o sulla stampante. <br />
<br />
Per poter produrre una [[Glossary#GUI | Graphical User Interface (GUI)]] usualmente si utilizza una sorta di Metodo di programmazione orientata agli oggetti (spesso facendo uso di [[Glossary#C Programming Language | C]] o di una delle sue varianti, o Visual Basic, o una delle [[Glossary#OO | OO]] varianti di Pascal quali [[Glossary#FreePascal | FreePascal]] con o senza [[Glossary#Lazarus | Lazarus]]). <br />
<br />
In una GUI all'utente vengono presentate schermate con un gran numero di immagini organizzate in modo strutturato, consistenti in un'insieme di strumenti o [[Glossary#Widget | Widgets]] che sono associati con varie azioni quali <br />
*selezioni da menu, <br />
*aperture o salvataggio files , <br />
*connessioni ad Internet, <br />
*esecuzioni di calcoli numerici, etc. <br />
<br />
L'utente dovrà muovere il mouse o qualche altro puntatore o strumento sullo schermo, per selezionare le azioni che saranno eseguite in risposta al click del mouse o ai tasti premuti.<br />
<br />
I sistemi per offrire una complessa interfaccia grafica possono essere scritti in Pascal standard o quasi qualsiasi altro linguaggio di programmazione, ma è molto più facile l'utilizzo di un sistema orientato agli oggetti, in cui ogni oggetto grafico sullo schermo può avere tutte le sue proprietà e le sue procedure e funzioni connesse con il suo uso conglobate in una struttura comune.<br />
<br />
<br />
== Oggetti - una analogia con il mondo reale == <br />
Consideriamo le analogie di un campione di sangue prelevato in un ospedale o in uno studio medico.<br />
=== Campione di sangue ===<br />
Il campione fisico è certamente un oggetto o '''object'''; ed ha , associato con esso una quantità di informazioni,documenti ed altri oggetti fisici. <br />
<br />
*'''Provetta''', del tipo determinato dal test che si dovrà eseguire.<br />
<br />
*'''Metodica''' (o ''metodo'', ''procedura operativa standard'') utilizzata dall'infermiera o dal tecnico di laboratorio che prelevano e processano il campione <br />
** che tipo di provetta si dovrà usare, <br />
**come processare il campione<br />
**come conservarlo prima di consegnarlo al laboratorio. <br />
<br />
*'''Etichetta''' sulla provetta con i dettagli per <br />
**identificare il campione <br />
**Nome e cognome e data di nascita del paziente <br />
** data e ora del prelievo <br />
** analisi richieste. <br />
<br />
*'''Modulo di richiesta''' che accompagna il campione per il laboratorio cui il campione è diretto <br />
** ID Campione<br />
**ID del medico richiedente<br />
** quali analisi il medico richiede e <br />
**anamnesi e dettagli completi del paziente<br />
**La possibile diagnosi di cui si richiede conferma. <br />
<br />
<br />
Una copia delle richiesta viene conservata nella cartella clinica per ricordare al medico di attendersi risultati entro un periodo di tempo adeguato. <br />
<br />
<br />
*In laboratorio - '''metodi locali''' per determinare <br />
**come il campione deve essere analizzato, <br />
**Quale strumento usare, <br />
**come lo strumento dovrà operare e come dovrà essere calibrato, <br />
**come il risultato dovrà essere memorizzato formattato e <br />
**presentato al medico. <br />
<br />
L'effettivo'' 'risultato''' è un dato che il medico usa per formulare la diagnosi, e una copia dei risultati è archiviata nella cartella clinica del paziente.<br />
<br />
Il campione fisico può essere conservato per riferimento,per test di conferma o ulteriori test, o potrà essere smaltito in ottemperanza alle norme per lo smaltimento dei campioni biologici o mediante incenerimento, ci sarà un metodo per descrivere questo procedimento.<br />
<br />
<br />
Non è necessario che il medico dica tutti i dettagli operativi e le istruzioni di lavoro ogni qualvolta che un campione viene prelevato; anzi,egli può avere ben poche conoscenze di come il campione verrà processato dal laboratorio. <br />
<br />
I dettagli dei vari processi sono'' '''ereditati''' dai precedenti processi dei campione in analisi ,ossia a priori si è stabilito il metodo di processo del campione - ci sarà un piano generico per l'intera sequenza, e insieme abbiamo potuto pensare al campione di sangue,a tutti i suoi documenti e dati, e la metodica di base, come a un complesso'' 'oggetto'''.<br />
<br />
<br />
<br />
Nella mente del medico, il campione di sangue è visto come un'unica entità, come i suoi risultati, e per gli infermieri e tecnici il campione, la provetta, l'etichetta e le condizioni di conservazione anch'esse sono identificate come se fossero una sola entità.<br />
<br />
Traduzione da completare.....<br />
<br />
=== Un'altro esempio- Automobile ===<br />
Se non vi piace l'esempio del campione di sangue,lo stesso tipo di ragionamento può essere applicato all'automobile consegnata al garage per una riparazione.<br />
Ciò potrebbe consistere in<br />
*Il veicolo fisico<br />
*i documenti in possesso del proprietario: Libretto di circolazione (comprese targhe), le assicurazioni, le ricevute per l'acquisto, i pezzi di ricambio, le riparazioni, ecc<br />
*il consumo di carburante<br />
*i conducenti autorizzati ad utilizzare il veicolo, con le loro patenti di guida<br />
*gli interventi di manutenzione registrati presso il garage<br />
*metodi o procedure da seguire per la verifica e la manutenzione di routine<br />
*metodi da seguire per le riparazioni non di routine, ecc<br />
*informazioni di fatturazione per il cliente<br />
<br />
== Esempi di programmazione ==<br />
<br />
Basta con questa introduzione, fatta di esempi del mondo reale! Dobbiamo procedere con l'obiettivo principale: la programmazione FreePascal<br />
<br />
<br />
<br />
Dobbiamo considerare la creazione di un semplice modulo con pochi controlli per una applicazione in FreePascal / Lazzaro.<br />
<br />
<div class="floatleft">[[Image:ObjectInspector-TForm.png]]</div><br />
<div class="floatright">[[Image:BlankForm.png]]</div><br />
<br />
<br />
Richiamando la IDE di Lazarus, al programmatore viene presentato un modello vuoto "Form" in progettazione, in cui egli è dovrà porre oggetti e vari controlli.<br />
<br />
Si noti che il Form vuoto precostituito è già un oggetto, con le proprie caratteristiche, come la posizione (in alto e sinistra), le dimensioni (altezza e larghezza), il colore, il font di default per l'aggiunta di testo ecc<br />
<br />
<br />
<br />
----<br />
<br />
If a Button control is placed on the Form (type TButton), it will have its own series of properties, which can be examined in the Object Inspector window. <br />
<br />
Several of the properties have names similar to those for the Form; this is because many properties are '''Inherited''' from some common Ancestor class, which lays out how properties are to be defined and handled by the descendant classes. <br />
<br />
As well as properties, the Object Inspector offers a tab called '''Events''', which gives access to Event Handlers which are methods instructing the application how to deal with things such as a mouse click on a button (OnClick) or some change in the position, size or other properties (OnChange).<br />
<br />
The physical image of the Button on the Form, together with all its properties and Event Handler methods, should be regarded as a single entity or '''Object''' in Pascal.<br />
<br />
<div class="floatleft">[[Image:ObjectInspector-TButton.png]]</div><br />
<div class="floatright">[[Image:FormWithButton.png]]</div><br />
<div class="floatright">[[Image:Source_FormWithButton1.png ]]</div><br />
<br />
== Object-Oriented Extensions to standard Pascal ==<br />
<br />
The Pascal record structure is extended by defining an <br />
=== Object ===<br />
<br />
An Object is a special kind of record. The record contains all the fields that<br />
are declared in the object's definition (just like a conventional record), but now procedures and functions can be declared as if they were part of the record and are held as pointers to the methods associated with the object's type. <br />
<br />
For example, an object could contain an array of real values, together with a Method for calculating the average.<br />
<br />
Type<br />
Average = Object<br />
NumVal: Integer;<br />
Values: Array [1..200] of Real;<br />
Function Mean: Real; { calculates the average value of the array }<br />
End;<br />
<br />
Objects can ”inherit” fields and methods from ”parent” objects. This means that these fields and methods can be used as if they were included in the objects declared as a ”child” object.<br />
<br />
Furthermore, a concept of visibility is introduced: fields, procedures and functions can be declared<br />
as public, protected or private. By default, fields and methods are public, and can be exported outside the<br />
current unit. Protected fields or methods are available only to objects descended from the current ancestor object. Fields or methods that are declared private are only accessible in the current unit:<br />
their scope is limited to the implementation of the current unit.<br />
<br />
=== Class ===<br />
Objects are not used very often by themselves in FreePascal and Lazarus; instead, Classes are used very widely. A Class is defined in almost the same way as an Object, but is a pointer to an Object rather than the Object itself. Technically, this means that the Class is allocated on the Heap of a program, whereas the Object is allocated on the Stack.<br />
<br />
Here is a simple example of a typical Class declaration:<br />
{-----------------------------------------}<br />
{example of Class declaration from the LCL}<br />
{-----------------------------------------}<br />
TPen = class(TFPCustomPen)<br />
private<br />
FColor: TColor;<br />
FPenHandleCached: boolean;<br />
FReference: TWSPenReference;<br />
procedure FreeReference;<br />
function GetHandle: HPEN;<br />
function GetReference: TWSPenReference;<br />
procedure ReferenceNeeded;<br />
procedure SetHandle(const Value: HPEN);<br />
protected<br />
procedure DoAllocateResources; override;<br />
procedure DoDeAllocateResources; override;<br />
procedure DoCopyProps(From: TFPCanvasHelper); override;<br />
procedure SetColor<br />
(const NewColor: TColor; const NewFPColor: TFPColor); virtual;<br />
procedure SetFPColor(const AValue: TFPColor); override;<br />
procedure SetColor(Value: TColor);<br />
procedure SetMode(Value: TPenMode); override;<br />
procedure SetStyle(Value: TPenStyle); override;<br />
procedure SetWidth(value: Integer); override;<br />
public<br />
constructor Create; override;<br />
destructor Destroy; override;<br />
procedure Assign(Source: TPersistent); override;<br />
property Handle: HPEN read GetHandle write SetHandle; deprecated;<br />
property Reference: TWSPenReference read GetReference;<br />
published<br />
property Color: TColor read FColor write SetColor default clBlack;<br />
property Mode default pmCopy;<br />
property Style default psSolid;<br />
property Width default 1;<br />
end;<br />
<br />
<br />
Note that this class is defined as an instance of another '''parent''' or '''ancestor''' class (''TFPCustomPen'') from which it '''inherits''' all its properties and methods. It has some fields of its own, grouped under<br />
*'''private''' - this means that items defined here are only available or visible to other classes or procedures/function defined within the same program unit (this example is from ''Graphics'', so any of the other classes such as ''TBitMap'', ''TPicture'' etc in the same unit can use them). They are essentially local variables (eg ''FColor'', ''FPenHandleCached'') or locally used methods (''GetHandle'', ''SetHandle'') but can be used or referred to in items declared in the '''protected''' or '''public''' sections.<br />
*'''protected''' - this means that items defined here are only available or visible to classes that are descended from this '''ancestor''' class, and inherit its properties or methods<br />
*'''public''' - this means that items defined here are available to any programming unit that includes the current unit in its [[Glossary#Uses | Uses]] clause <br />
*'''published''' - is the same as a '''public''' section, but the compiler also generates type information that is needed for automatic streaming of these classes. Often the list of published items appear in the Object Inspector of Lazarus; if there is no '''published''' list, all the '''public''' fields usually appear in the Object Inspector.<br />
<br />
=== Methods ===<br />
A method is just like a standard procedure or function, but can have some additional '''directives'''.<br />
<br />
Some of the methods defined above are labelled with the directive '''virtual'''; others are labelled with the '''override''' directive.<br />
*'''virtual''' means that the type or actual instance of a method is not known at compile-time, but is selected at run-time depending on what sub-program actually calls the method. It could be considered a place-holder in the definition of the class.<br />
*'''override''' means that at run-time the locally given definition can take the place of a definition inherited from an ancestor class, particularly if it was '''virtual'''. If you particularly want to use the method defined in the ancestor class, it is sometimes necessary to call it specifically with the '''inherited''' clause.<br />
<br />
Methods with no virtual or override directive are '''static''' methods (the usual kind in Pascal). Those with a virtual or override directive are '''dynamic'''.<br />
<br />
Special instances of methods are:<br />
*'''create''' - a '''constructor''' for a class, which takes care of allocating memory, collecting together all the information needed and configuring/initializing the various properties.<br />
*'''destroy''' - a '''destructor''' for a class, which removes all the parts of the class from the system in an orderly and logical way, and returns all its resources for the system to re-use.<br />
<br />
=== Properties ===<br />
<br />
Properties are just like ordinary fields in a conventional Pascal record, but they can have '''read''' and/or '''write''' specifiers.<br />
*'''read''' specifier is a field, or a function that returns a result of the correct type for the property. In the example above, the property ''Color'' has a read specifier ''FColor'', which is a local variable containing the value to be used. If a property has a '''read''' but no '''write''' specifier, it is read-only.<br />
*'''write''' specifier is a field, or a procedure that will store the value of the property in a specific location. In the example above, ''Color'' has a write specifier ''SetColor'' that is a procedure (defined in the '''protected''' section) for writing the color value to some specified location. If a property has a '''write''' but no '''read''' specifier, it is write-only.<br />
*'''default''' - note that it is possible to set a '''default''' value for a property. For example, ''Color'' here is given the default value ''clBlack'', or black, at the time of creation. It could subsequently be given a different value, by a programming assignment statement, or in the Object Inspector.<br />
<br />
<br />
== Further information ==<br />
<br />
This has only scratched the surface of the topic. For more details, readers are strongly recommended to read the [http://lazarus-ccr.sourceforge.net/fpcdoc/ref/ref.html FreePascal] manuals, especially Chapters 5 ('''Objects''') and 6 ('''Classes''')<br />
<br />
--[[User:Kirkpatc|Kirkpatc]] 11:04, 20 July 2008 (CEST)<br />
<br />
----<br />
[[Console Mode Pascal]]</div>Amedeohttps://wiki.freepascal.org/index.php?title=Object_Oriented_Programming_with_Free_Pascal_and_Lazarus/it&diff=34752Object Oriented Programming with Free Pascal and Lazarus/it2009-03-31T11:57:45Z<p>Amedeo: /* Programming Example */</p>
<hr />
<div>{{Object_Oriented_Programming_with_FreePascal_and_Lazarus}}<br />
<br />
Esistono molte guide eccellenti su Pascal, ma questa guida tenta di coinvolgere ulteriormente il principiante , nella programmazione orientata agli oggetti o [[Glossary#OO | Object-Oriented Programming]], che è un'estensione dello standard pascal, offerta da Turbo pascal, Delphi e FreePascal/Lazarus.<br />
<br />
Un [[Glossary#Object | Object]] è un'estensione della struttura standard pascal detta [http://wiki.lazarus.freepascal.org/Record record]<br />
<br />
La programmazione Pascal in testo standard è adatta alla creazione di applicazioni che, come le applicazioni Unix tradizionali,sono adatte per fare una cosa e per farla molto bene.<br />
<br />
Ciò che un programma fa può essere un'azione veramente complicata ,e può offrire all'utente molte opzioni di menu,<br />
ma è essenzialmente ristretta ad obbedire a comandi che l'utente digita da tastiera e a listare le sue risposte sul terminale o sulla stampante. <br />
<br />
Per poter produrre una [[Glossary#GUI | Graphical User Interface (GUI)]] usualmente si utilizza una sorta di Metodo di programmazione orientata agli oggetti (spesso facendo uso di [[Glossary#C Programming Language | C]] o di una delle sue varianti, o Visual Basic, o una delle [[Glossary#OO | OO]] varianti di Pascal quali [[Glossary#FreePascal | FreePascal]] con o senza [[Glossary#Lazarus | Lazarus]]). <br />
<br />
In una GUI all'utente vengono presentate schermate con un gran numero di immagini organizzate in modo strutturato, consistenti in un'insieme di strumenti o [[Glossary#Widget | Widgets]] che sono associati con varie azioni quali <br />
*selezioni da menu, <br />
*aperture o salvataggio files , <br />
*connessioni ad Internet, <br />
*esecuzioni di calcoli numerici, etc. <br />
<br />
L'utente dovrà muovere il mouse o qualche altro puntatore o strumento sullo schermo, per selezionare le azioni che saranno eseguite in risposta al click del mouse o ai tasti premuti.<br />
<br />
I sistemi per offrire una complessa interfaccia grafica possono essere scritti in Pascal standard o quasi qualsiasi altro linguaggio di programmazione, ma è molto più facile l'utilizzo di un sistema orientato agli oggetti, in cui ogni oggetto grafico sullo schermo può avere tutte le sue proprietà e le sue procedure e funzioni connesse con il suo uso conglobate in una struttura comune.<br />
<br />
<br />
== Oggetti - una analogia con il mondo reale == <br />
Consideriamo le analogie di un campione di sangue prelevato in un ospedale o in uno studio medico.<br />
=== Campione di sangue ===<br />
Il campione fisico è certamente un oggetto o '''object'''; ed ha , associato con esso una quantità di informazioni,documenti ed altri oggetti fisici. <br />
<br />
*'''Provetta''', del tipo determinato dal test che si dovrà eseguire.<br />
<br />
*'''Metodica''' (o ''metodo'', ''procedura operativa standard'') utilizzata dall'infermiera o dal tecnico di laboratorio che prelevano e processano il campione <br />
** che tipo di provetta si dovrà usare, <br />
**come processare il campione<br />
**come conservarlo prima di consegnarlo al laboratorio. <br />
<br />
*'''Etichetta''' sulla provetta con i dettagli per <br />
**identificare il campione <br />
**Nome e cognome e data di nascita del paziente <br />
** data e ora del prelievo <br />
** analisi richieste. <br />
<br />
*'''Modulo di richiesta''' che accompagna il campione per il laboratorio cui il campione è diretto <br />
** ID Campione<br />
**ID del medico richiedente<br />
** quali analisi il medico richiede e <br />
**anamnesi e dettagli completi del paziente<br />
**La possibile diagnosi di cui si richiede conferma. <br />
<br />
<br />
Una copia delle richiesta viene conservata nella cartella clinica per ricordare al medico di attendersi risultati entro un periodo di tempo adeguato. <br />
<br />
<br />
*In laboratorio - '''metodi locali''' per determinare <br />
**come il campione deve essere analizzato, <br />
**Quale strumento usare, <br />
**come lo strumento dovrà operare e come dovrà essere calibrato, <br />
**come il risultato dovrà essere memorizzato formattato e <br />
**presentato al medico. <br />
<br />
L'effettivo'' 'risultato''' è un dato che il medico usa per formulare la diagnosi, e una copia dei risultati è archiviata nella cartella clinica del paziente.<br />
<br />
Il campione fisico può essere conservato per riferimento,per test di conferma o ulteriori test, o potrà essere smaltito in ottemperanza alle norme per lo smaltimento dei campioni biologici o mediante incenerimento, ci sarà un metodo per descrivere questo procedimento.<br />
<br />
<br />
Non è necessario che il medico dica tutti i dettagli operativi e le istruzioni di lavoro ogni qualvolta che un campione viene prelevato; anzi,egli può avere ben poche conoscenze di come il campione verrà processato dal laboratorio. <br />
<br />
I dettagli dei vari processi sono'' '''ereditati''' dai precedenti processi dei campione in analisi ,ossia a priori si è stabilito il metodo di processo del campione - ci sarà un piano generico per l'intera sequenza, e insieme abbiamo potuto pensare al campione di sangue,a tutti i suoi documenti e dati, e la metodica di base, come a un complesso'' 'oggetto'''.<br />
<br />
<br />
<br />
Nella mente del medico, il campione di sangue è visto come un'unica entità, come i suoi risultati, e per gli infermieri e tecnici il campione, la provetta, l'etichetta e le condizioni di conservazione anch'esse sono identificate come se fossero una sola entità.<br />
<br />
Traduzione da completare.....<br />
<br />
=== Un'altro esempio- Automobile ===<br />
Se non vi piace l'esempio del campione di sangue,lo stesso tipo di ragionamento può essere applicato all'automobile consegnata al garage per una riparazione.<br />
Ciò potrebbe consistere in<br />
*Il veicolo fisico<br />
*i documenti in possesso del proprietario: Libretto di circolazione (comprese targhe), le assicurazioni, le ricevute per l'acquisto, i pezzi di ricambio, le riparazioni, ecc<br />
*il consumo di carburante<br />
*i conducenti autorizzati ad utilizzare il veicolo, con le loro patenti di guida<br />
*gli interventi di manutenzione registrati presso il garage<br />
*metodi o procedure da seguire per la verifica e la manutenzione di routine<br />
*metodi da seguire per le riparazioni non di routine, ecc<br />
*informazioni di fatturazione per il cliente<br />
<br />
== Esempi di programmazione ==<br />
<br />
Basta con questa introduzione, fatta di esempi del mondo reale! Dobbiamo procedere con l'obiettivo principale: la programmazione FreePascal<br />
<br />
<br />
Let us consider the creation of a simple Form with a few controls for an application in FreePascal/Lazarus.<br />
<br />
<div class="floatleft">[[Image:ObjectInspector-TForm.png]]</div><br />
<div class="floatright">[[Image:BlankForm.png]]</div><br />
<br />
On invoking the Lazarus IDE, the programmer is presented with a blank template Form design, on which he is encouraged to place various controls or objects.<br />
<br />
Note that the pre-made blank Form is already an Object, with its own properties such as position (Top and Left), size (Height and Width), colour, default font for adding text etc.<br />
<br />
<br />
<br />
----<br />
<br />
If a Button control is placed on the Form (type TButton), it will have its own series of properties, which can be examined in the Object Inspector window. <br />
<br />
Several of the properties have names similar to those for the Form; this is because many properties are '''Inherited''' from some common Ancestor class, which lays out how properties are to be defined and handled by the descendant classes. <br />
<br />
As well as properties, the Object Inspector offers a tab called '''Events''', which gives access to Event Handlers which are methods instructing the application how to deal with things such as a mouse click on a button (OnClick) or some change in the position, size or other properties (OnChange).<br />
<br />
The physical image of the Button on the Form, together with all its properties and Event Handler methods, should be regarded as a single entity or '''Object''' in Pascal.<br />
<br />
<div class="floatleft">[[Image:ObjectInspector-TButton.png]]</div><br />
<div class="floatright">[[Image:FormWithButton.png]]</div><br />
<div class="floatright">[[Image:Source_FormWithButton1.png ]]</div><br />
<br />
== Object-Oriented Extensions to standard Pascal ==<br />
<br />
The Pascal record structure is extended by defining an <br />
=== Object ===<br />
<br />
An Object is a special kind of record. The record contains all the fields that<br />
are declared in the object's definition (just like a conventional record), but now procedures and functions can be declared as if they were part of the record and are held as pointers to the methods associated with the object's type. <br />
<br />
For example, an object could contain an array of real values, together with a Method for calculating the average.<br />
<br />
Type<br />
Average = Object<br />
NumVal: Integer;<br />
Values: Array [1..200] of Real;<br />
Function Mean: Real; { calculates the average value of the array }<br />
End;<br />
<br />
Objects can ”inherit” fields and methods from ”parent” objects. This means that these fields and methods can be used as if they were included in the objects declared as a ”child” object.<br />
<br />
Furthermore, a concept of visibility is introduced: fields, procedures and functions can be declared<br />
as public, protected or private. By default, fields and methods are public, and can be exported outside the<br />
current unit. Protected fields or methods are available only to objects descended from the current ancestor object. Fields or methods that are declared private are only accessible in the current unit:<br />
their scope is limited to the implementation of the current unit.<br />
<br />
=== Class ===<br />
Objects are not used very often by themselves in FreePascal and Lazarus; instead, Classes are used very widely. A Class is defined in almost the same way as an Object, but is a pointer to an Object rather than the Object itself. Technically, this means that the Class is allocated on the Heap of a program, whereas the Object is allocated on the Stack.<br />
<br />
Here is a simple example of a typical Class declaration:<br />
{-----------------------------------------}<br />
{example of Class declaration from the LCL}<br />
{-----------------------------------------}<br />
TPen = class(TFPCustomPen)<br />
private<br />
FColor: TColor;<br />
FPenHandleCached: boolean;<br />
FReference: TWSPenReference;<br />
procedure FreeReference;<br />
function GetHandle: HPEN;<br />
function GetReference: TWSPenReference;<br />
procedure ReferenceNeeded;<br />
procedure SetHandle(const Value: HPEN);<br />
protected<br />
procedure DoAllocateResources; override;<br />
procedure DoDeAllocateResources; override;<br />
procedure DoCopyProps(From: TFPCanvasHelper); override;<br />
procedure SetColor<br />
(const NewColor: TColor; const NewFPColor: TFPColor); virtual;<br />
procedure SetFPColor(const AValue: TFPColor); override;<br />
procedure SetColor(Value: TColor);<br />
procedure SetMode(Value: TPenMode); override;<br />
procedure SetStyle(Value: TPenStyle); override;<br />
procedure SetWidth(value: Integer); override;<br />
public<br />
constructor Create; override;<br />
destructor Destroy; override;<br />
procedure Assign(Source: TPersistent); override;<br />
property Handle: HPEN read GetHandle write SetHandle; deprecated;<br />
property Reference: TWSPenReference read GetReference;<br />
published<br />
property Color: TColor read FColor write SetColor default clBlack;<br />
property Mode default pmCopy;<br />
property Style default psSolid;<br />
property Width default 1;<br />
end;<br />
<br />
<br />
Note that this class is defined as an instance of another '''parent''' or '''ancestor''' class (''TFPCustomPen'') from which it '''inherits''' all its properties and methods. It has some fields of its own, grouped under<br />
*'''private''' - this means that items defined here are only available or visible to other classes or procedures/function defined within the same program unit (this example is from ''Graphics'', so any of the other classes such as ''TBitMap'', ''TPicture'' etc in the same unit can use them). They are essentially local variables (eg ''FColor'', ''FPenHandleCached'') or locally used methods (''GetHandle'', ''SetHandle'') but can be used or referred to in items declared in the '''protected''' or '''public''' sections.<br />
*'''protected''' - this means that items defined here are only available or visible to classes that are descended from this '''ancestor''' class, and inherit its properties or methods<br />
*'''public''' - this means that items defined here are available to any programming unit that includes the current unit in its [[Glossary#Uses | Uses]] clause <br />
*'''published''' - is the same as a '''public''' section, but the compiler also generates type information that is needed for automatic streaming of these classes. Often the list of published items appear in the Object Inspector of Lazarus; if there is no '''published''' list, all the '''public''' fields usually appear in the Object Inspector.<br />
<br />
=== Methods ===<br />
A method is just like a standard procedure or function, but can have some additional '''directives'''.<br />
<br />
Some of the methods defined above are labelled with the directive '''virtual'''; others are labelled with the '''override''' directive.<br />
*'''virtual''' means that the type or actual instance of a method is not known at compile-time, but is selected at run-time depending on what sub-program actually calls the method. It could be considered a place-holder in the definition of the class.<br />
*'''override''' means that at run-time the locally given definition can take the place of a definition inherited from an ancestor class, particularly if it was '''virtual'''. If you particularly want to use the method defined in the ancestor class, it is sometimes necessary to call it specifically with the '''inherited''' clause.<br />
<br />
Methods with no virtual or override directive are '''static''' methods (the usual kind in Pascal). Those with a virtual or override directive are '''dynamic'''.<br />
<br />
Special instances of methods are:<br />
*'''create''' - a '''constructor''' for a class, which takes care of allocating memory, collecting together all the information needed and configuring/initializing the various properties.<br />
*'''destroy''' - a '''destructor''' for a class, which removes all the parts of the class from the system in an orderly and logical way, and returns all its resources for the system to re-use.<br />
<br />
=== Properties ===<br />
<br />
Properties are just like ordinary fields in a conventional Pascal record, but they can have '''read''' and/or '''write''' specifiers.<br />
*'''read''' specifier is a field, or a function that returns a result of the correct type for the property. In the example above, the property ''Color'' has a read specifier ''FColor'', which is a local variable containing the value to be used. If a property has a '''read''' but no '''write''' specifier, it is read-only.<br />
*'''write''' specifier is a field, or a procedure that will store the value of the property in a specific location. In the example above, ''Color'' has a write specifier ''SetColor'' that is a procedure (defined in the '''protected''' section) for writing the color value to some specified location. If a property has a '''write''' but no '''read''' specifier, it is write-only.<br />
*'''default''' - note that it is possible to set a '''default''' value for a property. For example, ''Color'' here is given the default value ''clBlack'', or black, at the time of creation. It could subsequently be given a different value, by a programming assignment statement, or in the Object Inspector.<br />
<br />
<br />
== Further information ==<br />
<br />
This has only scratched the surface of the topic. For more details, readers are strongly recommended to read the [http://lazarus-ccr.sourceforge.net/fpcdoc/ref/ref.html FreePascal] manuals, especially Chapters 5 ('''Objects''') and 6 ('''Classes''')<br />
<br />
--[[User:Kirkpatc|Kirkpatc]] 11:04, 20 July 2008 (CEST)<br />
<br />
----<br />
[[Console Mode Pascal]]</div>Amedeohttps://wiki.freepascal.org/index.php?title=Object_Oriented_Programming_with_Free_Pascal_and_Lazarus/it&diff=34751Object Oriented Programming with Free Pascal and Lazarus/it2009-03-31T11:42:28Z<p>Amedeo: /* Another Example - Automobile */</p>
<hr />
<div>{{Object_Oriented_Programming_with_FreePascal_and_Lazarus}}<br />
<br />
Esistono molte guide eccellenti su Pascal, ma questa guida tenta di coinvolgere ulteriormente il principiante , nella programmazione orientata agli oggetti o [[Glossary#OO | Object-Oriented Programming]], che è un'estensione dello standard pascal, offerta da Turbo pascal, Delphi e FreePascal/Lazarus.<br />
<br />
Un [[Glossary#Object | Object]] è un'estensione della struttura standard pascal detta [http://wiki.lazarus.freepascal.org/Record record]<br />
<br />
La programmazione Pascal in testo standard è adatta alla creazione di applicazioni che, come le applicazioni Unix tradizionali,sono adatte per fare una cosa e per farla molto bene.<br />
<br />
Ciò che un programma fa può essere un'azione veramente complicata ,e può offrire all'utente molte opzioni di menu,<br />
ma è essenzialmente ristretta ad obbedire a comandi che l'utente digita da tastiera e a listare le sue risposte sul terminale o sulla stampante. <br />
<br />
Per poter produrre una [[Glossary#GUI | Graphical User Interface (GUI)]] usualmente si utilizza una sorta di Metodo di programmazione orientata agli oggetti (spesso facendo uso di [[Glossary#C Programming Language | C]] o di una delle sue varianti, o Visual Basic, o una delle [[Glossary#OO | OO]] varianti di Pascal quali [[Glossary#FreePascal | FreePascal]] con o senza [[Glossary#Lazarus | Lazarus]]). <br />
<br />
In una GUI all'utente vengono presentate schermate con un gran numero di immagini organizzate in modo strutturato, consistenti in un'insieme di strumenti o [[Glossary#Widget | Widgets]] che sono associati con varie azioni quali <br />
*selezioni da menu, <br />
*aperture o salvataggio files , <br />
*connessioni ad Internet, <br />
*esecuzioni di calcoli numerici, etc. <br />
<br />
L'utente dovrà muovere il mouse o qualche altro puntatore o strumento sullo schermo, per selezionare le azioni che saranno eseguite in risposta al click del mouse o ai tasti premuti.<br />
<br />
I sistemi per offrire una complessa interfaccia grafica possono essere scritti in Pascal standard o quasi qualsiasi altro linguaggio di programmazione, ma è molto più facile l'utilizzo di un sistema orientato agli oggetti, in cui ogni oggetto grafico sullo schermo può avere tutte le sue proprietà e le sue procedure e funzioni connesse con il suo uso conglobate in una struttura comune.<br />
<br />
<br />
== Oggetti - una analogia con il mondo reale == <br />
Consideriamo le analogie di un campione di sangue prelevato in un ospedale o in uno studio medico.<br />
=== Campione di sangue ===<br />
Il campione fisico è certamente un oggetto o '''object'''; ed ha , associato con esso una quantità di informazioni,documenti ed altri oggetti fisici. <br />
<br />
*'''Provetta''', del tipo determinato dal test che si dovrà eseguire.<br />
<br />
*'''Metodica''' (o ''metodo'', ''procedura operativa standard'') utilizzata dall'infermiera o dal tecnico di laboratorio che prelevano e processano il campione <br />
** che tipo di provetta si dovrà usare, <br />
**come processare il campione<br />
**come conservarlo prima di consegnarlo al laboratorio. <br />
<br />
*'''Etichetta''' sulla provetta con i dettagli per <br />
**identificare il campione <br />
**Nome e cognome e data di nascita del paziente <br />
** data e ora del prelievo <br />
** analisi richieste. <br />
<br />
*'''Modulo di richiesta''' che accompagna il campione per il laboratorio cui il campione è diretto <br />
** ID Campione<br />
**ID del medico richiedente<br />
** quali analisi il medico richiede e <br />
**anamnesi e dettagli completi del paziente<br />
**La possibile diagnosi di cui si richiede conferma. <br />
<br />
<br />
Una copia delle richiesta viene conservata nella cartella clinica per ricordare al medico di attendersi risultati entro un periodo di tempo adeguato. <br />
<br />
<br />
*In laboratorio - '''metodi locali''' per determinare <br />
**come il campione deve essere analizzato, <br />
**Quale strumento usare, <br />
**come lo strumento dovrà operare e come dovrà essere calibrato, <br />
**come il risultato dovrà essere memorizzato formattato e <br />
**presentato al medico. <br />
<br />
L'effettivo'' 'risultato''' è un dato che il medico usa per formulare la diagnosi, e una copia dei risultati è archiviata nella cartella clinica del paziente.<br />
<br />
Il campione fisico può essere conservato per riferimento,per test di conferma o ulteriori test, o potrà essere smaltito in ottemperanza alle norme per lo smaltimento dei campioni biologici o mediante incenerimento, ci sarà un metodo per descrivere questo procedimento.<br />
<br />
<br />
Non è necessario che il medico dica tutti i dettagli operativi e le istruzioni di lavoro ogni qualvolta che un campione viene prelevato; anzi,egli può avere ben poche conoscenze di come il campione verrà processato dal laboratorio. <br />
<br />
I dettagli dei vari processi sono'' '''ereditati''' dai precedenti processi dei campione in analisi ,ossia a priori si è stabilito il metodo di processo del campione - ci sarà un piano generico per l'intera sequenza, e insieme abbiamo potuto pensare al campione di sangue,a tutti i suoi documenti e dati, e la metodica di base, come a un complesso'' 'oggetto'''.<br />
<br />
<br />
<br />
Nella mente del medico, il campione di sangue è visto come un'unica entità, come i suoi risultati, e per gli infermieri e tecnici il campione, la provetta, l'etichetta e le condizioni di conservazione anch'esse sono identificate come se fossero una sola entità.<br />
<br />
Traduzione da completare.....<br />
<br />
=== Un'altro esempio- Automobile ===<br />
Se non vi piace l'esempio del campione di sangue,lo stesso tipo di ragionamento può essere applicato all'automobile consegnata al garage per una riparazione.<br />
Ciò potrebbe consistere in<br />
*Il veicolo fisico<br />
*i documenti in possesso del proprietario: Libretto di circolazione (comprese targhe), le assicurazioni, le ricevute per l'acquisto, i pezzi di ricambio, le riparazioni, ecc<br />
*il consumo di carburante<br />
*i conducenti autorizzati ad utilizzare il veicolo, con le loro patenti di guida<br />
*gli interventi di manutenzione registrati presso il garage<br />
*metodi o procedure da seguire per la verifica e la manutenzione di routine<br />
*metodi da seguire per le riparazioni non di routine, ecc<br />
*informazioni di fatturazione per il cliente<br />
<br />
== Programming Example ==<br />
<br />
Enough of this pre-occupation with Real-World examples! Let us proceed to the main purpose: programming in FreePascal.<br />
<br />
Let us consider the creation of a simple Form with a few controls for an application in FreePascal/Lazarus.<br />
<br />
<div class="floatleft">[[Image:ObjectInspector-TForm.png]]</div><br />
<div class="floatright">[[Image:BlankForm.png]]</div><br />
<br />
On invoking the Lazarus IDE, the programmer is presented with a blank template Form design, on which he is encouraged to place various controls or objects.<br />
<br />
Note that the pre-made blank Form is already an Object, with its own properties such as position (Top and Left), size (Height and Width), colour, default font for adding text etc.<br />
<br />
<br />
<br />
----<br />
<br />
If a Button control is placed on the Form (type TButton), it will have its own series of properties, which can be examined in the Object Inspector window. <br />
<br />
Several of the properties have names similar to those for the Form; this is because many properties are '''Inherited''' from some common Ancestor class, which lays out how properties are to be defined and handled by the descendant classes. <br />
<br />
As well as properties, the Object Inspector offers a tab called '''Events''', which gives access to Event Handlers which are methods instructing the application how to deal with things such as a mouse click on a button (OnClick) or some change in the position, size or other properties (OnChange).<br />
<br />
The physical image of the Button on the Form, together with all its properties and Event Handler methods, should be regarded as a single entity or '''Object''' in Pascal.<br />
<br />
<div class="floatleft">[[Image:ObjectInspector-TButton.png]]</div><br />
<div class="floatright">[[Image:FormWithButton.png]]</div><br />
<div class="floatright">[[Image:Source_FormWithButton1.png ]]</div><br />
<br />
== Object-Oriented Extensions to standard Pascal ==<br />
<br />
The Pascal record structure is extended by defining an <br />
=== Object ===<br />
<br />
An Object is a special kind of record. The record contains all the fields that<br />
are declared in the object's definition (just like a conventional record), but now procedures and functions can be declared as if they were part of the record and are held as pointers to the methods associated with the object's type. <br />
<br />
For example, an object could contain an array of real values, together with a Method for calculating the average.<br />
<br />
Type<br />
Average = Object<br />
NumVal: Integer;<br />
Values: Array [1..200] of Real;<br />
Function Mean: Real; { calculates the average value of the array }<br />
End;<br />
<br />
Objects can ”inherit” fields and methods from ”parent” objects. This means that these fields and methods can be used as if they were included in the objects declared as a ”child” object.<br />
<br />
Furthermore, a concept of visibility is introduced: fields, procedures and functions can be declared<br />
as public, protected or private. By default, fields and methods are public, and can be exported outside the<br />
current unit. Protected fields or methods are available only to objects descended from the current ancestor object. Fields or methods that are declared private are only accessible in the current unit:<br />
their scope is limited to the implementation of the current unit.<br />
<br />
=== Class ===<br />
Objects are not used very often by themselves in FreePascal and Lazarus; instead, Classes are used very widely. A Class is defined in almost the same way as an Object, but is a pointer to an Object rather than the Object itself. Technically, this means that the Class is allocated on the Heap of a program, whereas the Object is allocated on the Stack.<br />
<br />
Here is a simple example of a typical Class declaration:<br />
{-----------------------------------------}<br />
{example of Class declaration from the LCL}<br />
{-----------------------------------------}<br />
TPen = class(TFPCustomPen)<br />
private<br />
FColor: TColor;<br />
FPenHandleCached: boolean;<br />
FReference: TWSPenReference;<br />
procedure FreeReference;<br />
function GetHandle: HPEN;<br />
function GetReference: TWSPenReference;<br />
procedure ReferenceNeeded;<br />
procedure SetHandle(const Value: HPEN);<br />
protected<br />
procedure DoAllocateResources; override;<br />
procedure DoDeAllocateResources; override;<br />
procedure DoCopyProps(From: TFPCanvasHelper); override;<br />
procedure SetColor<br />
(const NewColor: TColor; const NewFPColor: TFPColor); virtual;<br />
procedure SetFPColor(const AValue: TFPColor); override;<br />
procedure SetColor(Value: TColor);<br />
procedure SetMode(Value: TPenMode); override;<br />
procedure SetStyle(Value: TPenStyle); override;<br />
procedure SetWidth(value: Integer); override;<br />
public<br />
constructor Create; override;<br />
destructor Destroy; override;<br />
procedure Assign(Source: TPersistent); override;<br />
property Handle: HPEN read GetHandle write SetHandle; deprecated;<br />
property Reference: TWSPenReference read GetReference;<br />
published<br />
property Color: TColor read FColor write SetColor default clBlack;<br />
property Mode default pmCopy;<br />
property Style default psSolid;<br />
property Width default 1;<br />
end;<br />
<br />
<br />
Note that this class is defined as an instance of another '''parent''' or '''ancestor''' class (''TFPCustomPen'') from which it '''inherits''' all its properties and methods. It has some fields of its own, grouped under<br />
*'''private''' - this means that items defined here are only available or visible to other classes or procedures/function defined within the same program unit (this example is from ''Graphics'', so any of the other classes such as ''TBitMap'', ''TPicture'' etc in the same unit can use them). They are essentially local variables (eg ''FColor'', ''FPenHandleCached'') or locally used methods (''GetHandle'', ''SetHandle'') but can be used or referred to in items declared in the '''protected''' or '''public''' sections.<br />
*'''protected''' - this means that items defined here are only available or visible to classes that are descended from this '''ancestor''' class, and inherit its properties or methods<br />
*'''public''' - this means that items defined here are available to any programming unit that includes the current unit in its [[Glossary#Uses | Uses]] clause <br />
*'''published''' - is the same as a '''public''' section, but the compiler also generates type information that is needed for automatic streaming of these classes. Often the list of published items appear in the Object Inspector of Lazarus; if there is no '''published''' list, all the '''public''' fields usually appear in the Object Inspector.<br />
<br />
=== Methods ===<br />
A method is just like a standard procedure or function, but can have some additional '''directives'''.<br />
<br />
Some of the methods defined above are labelled with the directive '''virtual'''; others are labelled with the '''override''' directive.<br />
*'''virtual''' means that the type or actual instance of a method is not known at compile-time, but is selected at run-time depending on what sub-program actually calls the method. It could be considered a place-holder in the definition of the class.<br />
*'''override''' means that at run-time the locally given definition can take the place of a definition inherited from an ancestor class, particularly if it was '''virtual'''. If you particularly want to use the method defined in the ancestor class, it is sometimes necessary to call it specifically with the '''inherited''' clause.<br />
<br />
Methods with no virtual or override directive are '''static''' methods (the usual kind in Pascal). Those with a virtual or override directive are '''dynamic'''.<br />
<br />
Special instances of methods are:<br />
*'''create''' - a '''constructor''' for a class, which takes care of allocating memory, collecting together all the information needed and configuring/initializing the various properties.<br />
*'''destroy''' - a '''destructor''' for a class, which removes all the parts of the class from the system in an orderly and logical way, and returns all its resources for the system to re-use.<br />
<br />
=== Properties ===<br />
<br />
Properties are just like ordinary fields in a conventional Pascal record, but they can have '''read''' and/or '''write''' specifiers.<br />
*'''read''' specifier is a field, or a function that returns a result of the correct type for the property. In the example above, the property ''Color'' has a read specifier ''FColor'', which is a local variable containing the value to be used. If a property has a '''read''' but no '''write''' specifier, it is read-only.<br />
*'''write''' specifier is a field, or a procedure that will store the value of the property in a specific location. In the example above, ''Color'' has a write specifier ''SetColor'' that is a procedure (defined in the '''protected''' section) for writing the color value to some specified location. If a property has a '''write''' but no '''read''' specifier, it is write-only.<br />
*'''default''' - note that it is possible to set a '''default''' value for a property. For example, ''Color'' here is given the default value ''clBlack'', or black, at the time of creation. It could subsequently be given a different value, by a programming assignment statement, or in the Object Inspector.<br />
<br />
<br />
== Further information ==<br />
<br />
This has only scratched the surface of the topic. For more details, readers are strongly recommended to read the [http://lazarus-ccr.sourceforge.net/fpcdoc/ref/ref.html FreePascal] manuals, especially Chapters 5 ('''Objects''') and 6 ('''Classes''')<br />
<br />
--[[User:Kirkpatc|Kirkpatc]] 11:04, 20 July 2008 (CEST)<br />
<br />
----<br />
[[Console Mode Pascal]]</div>Amedeohttps://wiki.freepascal.org/index.php?title=Object_Oriented_Programming_with_Free_Pascal_and_Lazarus/it&diff=34750Object Oriented Programming with Free Pascal and Lazarus/it2009-03-31T11:08:22Z<p>Amedeo: /* Campione di sangue */</p>
<hr />
<div>{{Object_Oriented_Programming_with_FreePascal_and_Lazarus}}<br />
<br />
Esistono molte guide eccellenti su Pascal, ma questa guida tenta di coinvolgere ulteriormente il principiante , nella programmazione orientata agli oggetti o [[Glossary#OO | Object-Oriented Programming]], che è un'estensione dello standard pascal, offerta da Turbo pascal, Delphi e FreePascal/Lazarus.<br />
<br />
Un [[Glossary#Object | Object]] è un'estensione della struttura standard pascal detta [http://wiki.lazarus.freepascal.org/Record record]<br />
<br />
La programmazione Pascal in testo standard è adatta alla creazione di applicazioni che, come le applicazioni Unix tradizionali,sono adatte per fare una cosa e per farla molto bene.<br />
<br />
Ciò che un programma fa può essere un'azione veramente complicata ,e può offrire all'utente molte opzioni di menu,<br />
ma è essenzialmente ristretta ad obbedire a comandi che l'utente digita da tastiera e a listare le sue risposte sul terminale o sulla stampante. <br />
<br />
Per poter produrre una [[Glossary#GUI | Graphical User Interface (GUI)]] usualmente si utilizza una sorta di Metodo di programmazione orientata agli oggetti (spesso facendo uso di [[Glossary#C Programming Language | C]] o di una delle sue varianti, o Visual Basic, o una delle [[Glossary#OO | OO]] varianti di Pascal quali [[Glossary#FreePascal | FreePascal]] con o senza [[Glossary#Lazarus | Lazarus]]). <br />
<br />
In una GUI all'utente vengono presentate schermate con un gran numero di immagini organizzate in modo strutturato, consistenti in un'insieme di strumenti o [[Glossary#Widget | Widgets]] che sono associati con varie azioni quali <br />
*selezioni da menu, <br />
*aperture o salvataggio files , <br />
*connessioni ad Internet, <br />
*esecuzioni di calcoli numerici, etc. <br />
<br />
L'utente dovrà muovere il mouse o qualche altro puntatore o strumento sullo schermo, per selezionare le azioni che saranno eseguite in risposta al click del mouse o ai tasti premuti.<br />
<br />
I sistemi per offrire una complessa interfaccia grafica possono essere scritti in Pascal standard o quasi qualsiasi altro linguaggio di programmazione, ma è molto più facile l'utilizzo di un sistema orientato agli oggetti, in cui ogni oggetto grafico sullo schermo può avere tutte le sue proprietà e le sue procedure e funzioni connesse con il suo uso conglobate in una struttura comune.<br />
<br />
<br />
== Oggetti - una analogia con il mondo reale == <br />
Consideriamo le analogie di un campione di sangue prelevato in un ospedale o in uno studio medico.<br />
=== Campione di sangue ===<br />
Il campione fisico è certamente un oggetto o '''object'''; ed ha , associato con esso una quantità di informazioni,documenti ed altri oggetti fisici. <br />
<br />
*'''Provetta''', del tipo determinato dal test che si dovrà eseguire.<br />
<br />
*'''Metodica''' (o ''metodo'', ''procedura operativa standard'') utilizzata dall'infermiera o dal tecnico di laboratorio che prelevano e processano il campione <br />
** che tipo di provetta si dovrà usare, <br />
**come processare il campione<br />
**come conservarlo prima di consegnarlo al laboratorio. <br />
<br />
*'''Etichetta''' sulla provetta con i dettagli per <br />
**identificare il campione <br />
**Nome e cognome e data di nascita del paziente <br />
** data e ora del prelievo <br />
** analisi richieste. <br />
<br />
*'''Modulo di richiesta''' che accompagna il campione per il laboratorio cui il campione è diretto <br />
** ID Campione<br />
**ID del medico richiedente<br />
** quali analisi il medico richiede e <br />
**anamnesi e dettagli completi del paziente<br />
**La possibile diagnosi di cui si richiede conferma. <br />
<br />
<br />
Una copia delle richiesta viene conservata nella cartella clinica per ricordare al medico di attendersi risultati entro un periodo di tempo adeguato. <br />
<br />
<br />
*In laboratorio - '''metodi locali''' per determinare <br />
**come il campione deve essere analizzato, <br />
**Quale strumento usare, <br />
**come lo strumento dovrà operare e come dovrà essere calibrato, <br />
**come il risultato dovrà essere memorizzato formattato e <br />
**presentato al medico. <br />
<br />
L'effettivo'' 'risultato''' è un dato che il medico usa per formulare la diagnosi, e una copia dei risultati è archiviata nella cartella clinica del paziente.<br />
<br />
Il campione fisico può essere conservato per riferimento,per test di conferma o ulteriori test, o potrà essere smaltito in ottemperanza alle norme per lo smaltimento dei campioni biologici o mediante incenerimento, ci sarà un metodo per descrivere questo procedimento.<br />
<br />
<br />
Non è necessario che il medico dica tutti i dettagli operativi e le istruzioni di lavoro ogni qualvolta che un campione viene prelevato; anzi,egli può avere ben poche conoscenze di come il campione verrà processato dal laboratorio. <br />
<br />
I dettagli dei vari processi sono'' '''ereditati''' dai precedenti processi dei campione in analisi ,ossia a priori si è stabilito il metodo di processo del campione - ci sarà un piano generico per l'intera sequenza, e insieme abbiamo potuto pensare al campione di sangue,a tutti i suoi documenti e dati, e la metodica di base, come a un complesso'' 'oggetto'''.<br />
<br />
<br />
<br />
Nella mente del medico, il campione di sangue è visto come un'unica entità, come i suoi risultati, e per gli infermieri e tecnici il campione, la provetta, l'etichetta e le condizioni di conservazione anch'esse sono identificate come se fossero una sola entità.<br />
<br />
Traduzione da completare.....<br />
<br />
=== Another Example - Automobile ===<br />
If you don't like blood, the same sort of reasoning could be applied to a car taken to a garage for repair.<br />
It might consist of:<br />
*the physical vehicle<br />
*documents held by the owner: registration or license (including license plates), insurance, receipts for purchase, parts, repairs etc<br />
*the fuel consumption history<br />
*the drivers allowed to use the vehicle, with their license particulars<br />
*service records held by the garage<br />
*methods or procedures to be followed for routine checking and maintenance<br />
*methods to be followed for non-routine repairs etc<br />
*billing information for the customer<br />
<br />
== Programming Example ==<br />
<br />
Enough of this pre-occupation with Real-World examples! Let us proceed to the main purpose: programming in FreePascal.<br />
<br />
Let us consider the creation of a simple Form with a few controls for an application in FreePascal/Lazarus.<br />
<br />
<div class="floatleft">[[Image:ObjectInspector-TForm.png]]</div><br />
<div class="floatright">[[Image:BlankForm.png]]</div><br />
<br />
On invoking the Lazarus IDE, the programmer is presented with a blank template Form design, on which he is encouraged to place various controls or objects.<br />
<br />
Note that the pre-made blank Form is already an Object, with its own properties such as position (Top and Left), size (Height and Width), colour, default font for adding text etc.<br />
<br />
<br />
<br />
----<br />
<br />
If a Button control is placed on the Form (type TButton), it will have its own series of properties, which can be examined in the Object Inspector window. <br />
<br />
Several of the properties have names similar to those for the Form; this is because many properties are '''Inherited''' from some common Ancestor class, which lays out how properties are to be defined and handled by the descendant classes. <br />
<br />
As well as properties, the Object Inspector offers a tab called '''Events''', which gives access to Event Handlers which are methods instructing the application how to deal with things such as a mouse click on a button (OnClick) or some change in the position, size or other properties (OnChange).<br />
<br />
The physical image of the Button on the Form, together with all its properties and Event Handler methods, should be regarded as a single entity or '''Object''' in Pascal.<br />
<br />
<div class="floatleft">[[Image:ObjectInspector-TButton.png]]</div><br />
<div class="floatright">[[Image:FormWithButton.png]]</div><br />
<div class="floatright">[[Image:Source_FormWithButton1.png ]]</div><br />
<br />
== Object-Oriented Extensions to standard Pascal ==<br />
<br />
The Pascal record structure is extended by defining an <br />
=== Object ===<br />
<br />
An Object is a special kind of record. The record contains all the fields that<br />
are declared in the object's definition (just like a conventional record), but now procedures and functions can be declared as if they were part of the record and are held as pointers to the methods associated with the object's type. <br />
<br />
For example, an object could contain an array of real values, together with a Method for calculating the average.<br />
<br />
Type<br />
Average = Object<br />
NumVal: Integer;<br />
Values: Array [1..200] of Real;<br />
Function Mean: Real; { calculates the average value of the array }<br />
End;<br />
<br />
Objects can ”inherit” fields and methods from ”parent” objects. This means that these fields and methods can be used as if they were included in the objects declared as a ”child” object.<br />
<br />
Furthermore, a concept of visibility is introduced: fields, procedures and functions can be declared<br />
as public, protected or private. By default, fields and methods are public, and can be exported outside the<br />
current unit. Protected fields or methods are available only to objects descended from the current ancestor object. Fields or methods that are declared private are only accessible in the current unit:<br />
their scope is limited to the implementation of the current unit.<br />
<br />
=== Class ===<br />
Objects are not used very often by themselves in FreePascal and Lazarus; instead, Classes are used very widely. A Class is defined in almost the same way as an Object, but is a pointer to an Object rather than the Object itself. Technically, this means that the Class is allocated on the Heap of a program, whereas the Object is allocated on the Stack.<br />
<br />
Here is a simple example of a typical Class declaration:<br />
{-----------------------------------------}<br />
{example of Class declaration from the LCL}<br />
{-----------------------------------------}<br />
TPen = class(TFPCustomPen)<br />
private<br />
FColor: TColor;<br />
FPenHandleCached: boolean;<br />
FReference: TWSPenReference;<br />
procedure FreeReference;<br />
function GetHandle: HPEN;<br />
function GetReference: TWSPenReference;<br />
procedure ReferenceNeeded;<br />
procedure SetHandle(const Value: HPEN);<br />
protected<br />
procedure DoAllocateResources; override;<br />
procedure DoDeAllocateResources; override;<br />
procedure DoCopyProps(From: TFPCanvasHelper); override;<br />
procedure SetColor<br />
(const NewColor: TColor; const NewFPColor: TFPColor); virtual;<br />
procedure SetFPColor(const AValue: TFPColor); override;<br />
procedure SetColor(Value: TColor);<br />
procedure SetMode(Value: TPenMode); override;<br />
procedure SetStyle(Value: TPenStyle); override;<br />
procedure SetWidth(value: Integer); override;<br />
public<br />
constructor Create; override;<br />
destructor Destroy; override;<br />
procedure Assign(Source: TPersistent); override;<br />
property Handle: HPEN read GetHandle write SetHandle; deprecated;<br />
property Reference: TWSPenReference read GetReference;<br />
published<br />
property Color: TColor read FColor write SetColor default clBlack;<br />
property Mode default pmCopy;<br />
property Style default psSolid;<br />
property Width default 1;<br />
end;<br />
<br />
<br />
Note that this class is defined as an instance of another '''parent''' or '''ancestor''' class (''TFPCustomPen'') from which it '''inherits''' all its properties and methods. It has some fields of its own, grouped under<br />
*'''private''' - this means that items defined here are only available or visible to other classes or procedures/function defined within the same program unit (this example is from ''Graphics'', so any of the other classes such as ''TBitMap'', ''TPicture'' etc in the same unit can use them). They are essentially local variables (eg ''FColor'', ''FPenHandleCached'') or locally used methods (''GetHandle'', ''SetHandle'') but can be used or referred to in items declared in the '''protected''' or '''public''' sections.<br />
*'''protected''' - this means that items defined here are only available or visible to classes that are descended from this '''ancestor''' class, and inherit its properties or methods<br />
*'''public''' - this means that items defined here are available to any programming unit that includes the current unit in its [[Glossary#Uses | Uses]] clause <br />
*'''published''' - is the same as a '''public''' section, but the compiler also generates type information that is needed for automatic streaming of these classes. Often the list of published items appear in the Object Inspector of Lazarus; if there is no '''published''' list, all the '''public''' fields usually appear in the Object Inspector.<br />
<br />
=== Methods ===<br />
A method is just like a standard procedure or function, but can have some additional '''directives'''.<br />
<br />
Some of the methods defined above are labelled with the directive '''virtual'''; others are labelled with the '''override''' directive.<br />
*'''virtual''' means that the type or actual instance of a method is not known at compile-time, but is selected at run-time depending on what sub-program actually calls the method. It could be considered a place-holder in the definition of the class.<br />
*'''override''' means that at run-time the locally given definition can take the place of a definition inherited from an ancestor class, particularly if it was '''virtual'''. If you particularly want to use the method defined in the ancestor class, it is sometimes necessary to call it specifically with the '''inherited''' clause.<br />
<br />
Methods with no virtual or override directive are '''static''' methods (the usual kind in Pascal). Those with a virtual or override directive are '''dynamic'''.<br />
<br />
Special instances of methods are:<br />
*'''create''' - a '''constructor''' for a class, which takes care of allocating memory, collecting together all the information needed and configuring/initializing the various properties.<br />
*'''destroy''' - a '''destructor''' for a class, which removes all the parts of the class from the system in an orderly and logical way, and returns all its resources for the system to re-use.<br />
<br />
=== Properties ===<br />
<br />
Properties are just like ordinary fields in a conventional Pascal record, but they can have '''read''' and/or '''write''' specifiers.<br />
*'''read''' specifier is a field, or a function that returns a result of the correct type for the property. In the example above, the property ''Color'' has a read specifier ''FColor'', which is a local variable containing the value to be used. If a property has a '''read''' but no '''write''' specifier, it is read-only.<br />
*'''write''' specifier is a field, or a procedure that will store the value of the property in a specific location. In the example above, ''Color'' has a write specifier ''SetColor'' that is a procedure (defined in the '''protected''' section) for writing the color value to some specified location. If a property has a '''write''' but no '''read''' specifier, it is write-only.<br />
*'''default''' - note that it is possible to set a '''default''' value for a property. For example, ''Color'' here is given the default value ''clBlack'', or black, at the time of creation. It could subsequently be given a different value, by a programming assignment statement, or in the Object Inspector.<br />
<br />
<br />
== Further information ==<br />
<br />
This has only scratched the surface of the topic. For more details, readers are strongly recommended to read the [http://lazarus-ccr.sourceforge.net/fpcdoc/ref/ref.html FreePascal] manuals, especially Chapters 5 ('''Objects''') and 6 ('''Classes''')<br />
<br />
--[[User:Kirkpatc|Kirkpatc]] 11:04, 20 July 2008 (CEST)<br />
<br />
----<br />
[[Console Mode Pascal]]</div>Amedeohttps://wiki.freepascal.org/index.php?title=Object_Oriented_Programming_with_Free_Pascal_and_Lazarus/it&diff=34749Object Oriented Programming with Free Pascal and Lazarus/it2009-03-31T11:07:27Z<p>Amedeo: /* Campione di sangue */</p>
<hr />
<div>{{Object_Oriented_Programming_with_FreePascal_and_Lazarus}}<br />
<br />
Esistono molte guide eccellenti su Pascal, ma questa guida tenta di coinvolgere ulteriormente il principiante , nella programmazione orientata agli oggetti o [[Glossary#OO | Object-Oriented Programming]], che è un'estensione dello standard pascal, offerta da Turbo pascal, Delphi e FreePascal/Lazarus.<br />
<br />
Un [[Glossary#Object | Object]] è un'estensione della struttura standard pascal detta [http://wiki.lazarus.freepascal.org/Record record]<br />
<br />
La programmazione Pascal in testo standard è adatta alla creazione di applicazioni che, come le applicazioni Unix tradizionali,sono adatte per fare una cosa e per farla molto bene.<br />
<br />
Ciò che un programma fa può essere un'azione veramente complicata ,e può offrire all'utente molte opzioni di menu,<br />
ma è essenzialmente ristretta ad obbedire a comandi che l'utente digita da tastiera e a listare le sue risposte sul terminale o sulla stampante. <br />
<br />
Per poter produrre una [[Glossary#GUI | Graphical User Interface (GUI)]] usualmente si utilizza una sorta di Metodo di programmazione orientata agli oggetti (spesso facendo uso di [[Glossary#C Programming Language | C]] o di una delle sue varianti, o Visual Basic, o una delle [[Glossary#OO | OO]] varianti di Pascal quali [[Glossary#FreePascal | FreePascal]] con o senza [[Glossary#Lazarus | Lazarus]]). <br />
<br />
In una GUI all'utente vengono presentate schermate con un gran numero di immagini organizzate in modo strutturato, consistenti in un'insieme di strumenti o [[Glossary#Widget | Widgets]] che sono associati con varie azioni quali <br />
*selezioni da menu, <br />
*aperture o salvataggio files , <br />
*connessioni ad Internet, <br />
*esecuzioni di calcoli numerici, etc. <br />
<br />
L'utente dovrà muovere il mouse o qualche altro puntatore o strumento sullo schermo, per selezionare le azioni che saranno eseguite in risposta al click del mouse o ai tasti premuti.<br />
<br />
I sistemi per offrire una complessa interfaccia grafica possono essere scritti in Pascal standard o quasi qualsiasi altro linguaggio di programmazione, ma è molto più facile l'utilizzo di un sistema orientato agli oggetti, in cui ogni oggetto grafico sullo schermo può avere tutte le sue proprietà e le sue procedure e funzioni connesse con il suo uso conglobate in una struttura comune.<br />
<br />
<br />
== Oggetti - una analogia con il mondo reale == <br />
Consideriamo le analogie di un campione di sangue prelevato in un ospedale o in uno studio medico.<br />
=== Campione di sangue ===<br />
Il campione fisico è certamente un oggetto o '''object'''; ed ha , associato con esso una quantità di informazioni,documenti ed altri oggetti fisici. <br />
<br />
*'''Provetta''', del tipo determinato dal test che si dovrà eseguire.<br />
<br />
*'''Metodica''' (o ''metodo'', ''procedura operativa standard'') utilizzata dall'infermiera o dal tecnico di laboratorio che prelevano e processano il campione <br />
** che tipo di provetta si dovrà usare, <br />
**come processare il campione<br />
**come conservarlo prima di consegnarlo al laboratorio. <br />
<br />
*'''Etichetta''' sulla provetta con i dettagli per <br />
**identificare il campione <br />
**Nome e cognome e data di nascita del paziente <br />
** data e ora del prelievo <br />
** analisi richieste. <br />
<br />
*'''Modulo di richiesta''' che accompagna il campione per il laboratorio cui il campione è diretto <br />
** ID Campione<br />
**ID del medico richiedente<br />
** quali analisi il medico richiede e <br />
**anamnesi e dettagli completi del paziente<br />
**La possibile diagnosi di cui si richiede conferma. <br />
<br />
<br />
Una copia delle richiesta viene conservata nella cartella clinica per ricordare al medico di attendersi risultati entro un periodo di tempo adeguato. <br />
<br />
<br />
*In laboratorio - '''metodi locali''' per determinare <br />
**come il campione deve essere analizzato, <br />
**Quale strumento usare, <br />
**come lo strumento dovrà operare e come dovrà essere calibrato, <br />
**come il risultato dovrà essere memorizzato formattato e <br />
**presentato al medico. <br />
<br />
L'effettivo'' 'risultato''' è un dato che il medico usa per formulare la diagnosi, e una copia dei risultati è archiviata nella cartella clinica del paziente.<br />
<br />
Il campione fisico può essere conservato per riferimento,per test di conferma o ulteriori test, o potrà essere smaltito in ottemperanza alle norme per lo smaltimento dei campioni biologici o mediante incenerimento, ci sarà un metodo per descrivere questo procedimento.<br />
<br />
<br />
Non è necessario che il medico dica tutti i dettagli operativi e le istruzioni di lavoro ogni qualvolta che un campione viene prelevato; anzi,egli può avere ben poche conoscenze di come il campione verrà processato dal laboratorio. <br />
<br />
I dettagli dei vari processi sono'' '''ereditati''' dai precedenti processi dei campione in analisi ,ossia a priori si è stabilito il metodo di processo del campione - ci sarà un piano generico per l'intera sequenza, e insieme abbiamo potuto pensare al campione di sangue,a tutti i suoi documenti e dati, e la metodica di base, come a un complesso'' 'oggetto'''.<br />
<br />
<br />
<br />
Nella mente del medico, il campione di sangue è visto quasi come un'unica entità, come i suoi risultati, e per gli infermieri e tecnici il campione, la provetta, l'etichetta e le condizioni di conservazione anch'esse come se fossero una sola entità.<br />
<br />
Traduzione da completare.....<br />
<br />
=== Another Example - Automobile ===<br />
If you don't like blood, the same sort of reasoning could be applied to a car taken to a garage for repair.<br />
It might consist of:<br />
*the physical vehicle<br />
*documents held by the owner: registration or license (including license plates), insurance, receipts for purchase, parts, repairs etc<br />
*the fuel consumption history<br />
*the drivers allowed to use the vehicle, with their license particulars<br />
*service records held by the garage<br />
*methods or procedures to be followed for routine checking and maintenance<br />
*methods to be followed for non-routine repairs etc<br />
*billing information for the customer<br />
<br />
== Programming Example ==<br />
<br />
Enough of this pre-occupation with Real-World examples! Let us proceed to the main purpose: programming in FreePascal.<br />
<br />
Let us consider the creation of a simple Form with a few controls for an application in FreePascal/Lazarus.<br />
<br />
<div class="floatleft">[[Image:ObjectInspector-TForm.png]]</div><br />
<div class="floatright">[[Image:BlankForm.png]]</div><br />
<br />
On invoking the Lazarus IDE, the programmer is presented with a blank template Form design, on which he is encouraged to place various controls or objects.<br />
<br />
Note that the pre-made blank Form is already an Object, with its own properties such as position (Top and Left), size (Height and Width), colour, default font for adding text etc.<br />
<br />
<br />
<br />
----<br />
<br />
If a Button control is placed on the Form (type TButton), it will have its own series of properties, which can be examined in the Object Inspector window. <br />
<br />
Several of the properties have names similar to those for the Form; this is because many properties are '''Inherited''' from some common Ancestor class, which lays out how properties are to be defined and handled by the descendant classes. <br />
<br />
As well as properties, the Object Inspector offers a tab called '''Events''', which gives access to Event Handlers which are methods instructing the application how to deal with things such as a mouse click on a button (OnClick) or some change in the position, size or other properties (OnChange).<br />
<br />
The physical image of the Button on the Form, together with all its properties and Event Handler methods, should be regarded as a single entity or '''Object''' in Pascal.<br />
<br />
<div class="floatleft">[[Image:ObjectInspector-TButton.png]]</div><br />
<div class="floatright">[[Image:FormWithButton.png]]</div><br />
<div class="floatright">[[Image:Source_FormWithButton1.png ]]</div><br />
<br />
== Object-Oriented Extensions to standard Pascal ==<br />
<br />
The Pascal record structure is extended by defining an <br />
=== Object ===<br />
<br />
An Object is a special kind of record. The record contains all the fields that<br />
are declared in the object's definition (just like a conventional record), but now procedures and functions can be declared as if they were part of the record and are held as pointers to the methods associated with the object's type. <br />
<br />
For example, an object could contain an array of real values, together with a Method for calculating the average.<br />
<br />
Type<br />
Average = Object<br />
NumVal: Integer;<br />
Values: Array [1..200] of Real;<br />
Function Mean: Real; { calculates the average value of the array }<br />
End;<br />
<br />
Objects can ”inherit” fields and methods from ”parent” objects. This means that these fields and methods can be used as if they were included in the objects declared as a ”child” object.<br />
<br />
Furthermore, a concept of visibility is introduced: fields, procedures and functions can be declared<br />
as public, protected or private. By default, fields and methods are public, and can be exported outside the<br />
current unit. Protected fields or methods are available only to objects descended from the current ancestor object. Fields or methods that are declared private are only accessible in the current unit:<br />
their scope is limited to the implementation of the current unit.<br />
<br />
=== Class ===<br />
Objects are not used very often by themselves in FreePascal and Lazarus; instead, Classes are used very widely. A Class is defined in almost the same way as an Object, but is a pointer to an Object rather than the Object itself. Technically, this means that the Class is allocated on the Heap of a program, whereas the Object is allocated on the Stack.<br />
<br />
Here is a simple example of a typical Class declaration:<br />
{-----------------------------------------}<br />
{example of Class declaration from the LCL}<br />
{-----------------------------------------}<br />
TPen = class(TFPCustomPen)<br />
private<br />
FColor: TColor;<br />
FPenHandleCached: boolean;<br />
FReference: TWSPenReference;<br />
procedure FreeReference;<br />
function GetHandle: HPEN;<br />
function GetReference: TWSPenReference;<br />
procedure ReferenceNeeded;<br />
procedure SetHandle(const Value: HPEN);<br />
protected<br />
procedure DoAllocateResources; override;<br />
procedure DoDeAllocateResources; override;<br />
procedure DoCopyProps(From: TFPCanvasHelper); override;<br />
procedure SetColor<br />
(const NewColor: TColor; const NewFPColor: TFPColor); virtual;<br />
procedure SetFPColor(const AValue: TFPColor); override;<br />
procedure SetColor(Value: TColor);<br />
procedure SetMode(Value: TPenMode); override;<br />
procedure SetStyle(Value: TPenStyle); override;<br />
procedure SetWidth(value: Integer); override;<br />
public<br />
constructor Create; override;<br />
destructor Destroy; override;<br />
procedure Assign(Source: TPersistent); override;<br />
property Handle: HPEN read GetHandle write SetHandle; deprecated;<br />
property Reference: TWSPenReference read GetReference;<br />
published<br />
property Color: TColor read FColor write SetColor default clBlack;<br />
property Mode default pmCopy;<br />
property Style default psSolid;<br />
property Width default 1;<br />
end;<br />
<br />
<br />
Note that this class is defined as an instance of another '''parent''' or '''ancestor''' class (''TFPCustomPen'') from which it '''inherits''' all its properties and methods. It has some fields of its own, grouped under<br />
*'''private''' - this means that items defined here are only available or visible to other classes or procedures/function defined within the same program unit (this example is from ''Graphics'', so any of the other classes such as ''TBitMap'', ''TPicture'' etc in the same unit can use them). They are essentially local variables (eg ''FColor'', ''FPenHandleCached'') or locally used methods (''GetHandle'', ''SetHandle'') but can be used or referred to in items declared in the '''protected''' or '''public''' sections.<br />
*'''protected''' - this means that items defined here are only available or visible to classes that are descended from this '''ancestor''' class, and inherit its properties or methods<br />
*'''public''' - this means that items defined here are available to any programming unit that includes the current unit in its [[Glossary#Uses | Uses]] clause <br />
*'''published''' - is the same as a '''public''' section, but the compiler also generates type information that is needed for automatic streaming of these classes. Often the list of published items appear in the Object Inspector of Lazarus; if there is no '''published''' list, all the '''public''' fields usually appear in the Object Inspector.<br />
<br />
=== Methods ===<br />
A method is just like a standard procedure or function, but can have some additional '''directives'''.<br />
<br />
Some of the methods defined above are labelled with the directive '''virtual'''; others are labelled with the '''override''' directive.<br />
*'''virtual''' means that the type or actual instance of a method is not known at compile-time, but is selected at run-time depending on what sub-program actually calls the method. It could be considered a place-holder in the definition of the class.<br />
*'''override''' means that at run-time the locally given definition can take the place of a definition inherited from an ancestor class, particularly if it was '''virtual'''. If you particularly want to use the method defined in the ancestor class, it is sometimes necessary to call it specifically with the '''inherited''' clause.<br />
<br />
Methods with no virtual or override directive are '''static''' methods (the usual kind in Pascal). Those with a virtual or override directive are '''dynamic'''.<br />
<br />
Special instances of methods are:<br />
*'''create''' - a '''constructor''' for a class, which takes care of allocating memory, collecting together all the information needed and configuring/initializing the various properties.<br />
*'''destroy''' - a '''destructor''' for a class, which removes all the parts of the class from the system in an orderly and logical way, and returns all its resources for the system to re-use.<br />
<br />
=== Properties ===<br />
<br />
Properties are just like ordinary fields in a conventional Pascal record, but they can have '''read''' and/or '''write''' specifiers.<br />
*'''read''' specifier is a field, or a function that returns a result of the correct type for the property. In the example above, the property ''Color'' has a read specifier ''FColor'', which is a local variable containing the value to be used. If a property has a '''read''' but no '''write''' specifier, it is read-only.<br />
*'''write''' specifier is a field, or a procedure that will store the value of the property in a specific location. In the example above, ''Color'' has a write specifier ''SetColor'' that is a procedure (defined in the '''protected''' section) for writing the color value to some specified location. If a property has a '''write''' but no '''read''' specifier, it is write-only.<br />
*'''default''' - note that it is possible to set a '''default''' value for a property. For example, ''Color'' here is given the default value ''clBlack'', or black, at the time of creation. It could subsequently be given a different value, by a programming assignment statement, or in the Object Inspector.<br />
<br />
<br />
== Further information ==<br />
<br />
This has only scratched the surface of the topic. For more details, readers are strongly recommended to read the [http://lazarus-ccr.sourceforge.net/fpcdoc/ref/ref.html FreePascal] manuals, especially Chapters 5 ('''Objects''') and 6 ('''Classes''')<br />
<br />
--[[User:Kirkpatc|Kirkpatc]] 11:04, 20 July 2008 (CEST)<br />
<br />
----<br />
[[Console Mode Pascal]]</div>Amedeohttps://wiki.freepascal.org/index.php?title=Object_Oriented_Programming_with_Free_Pascal_and_Lazarus/it&diff=34748Object Oriented Programming with Free Pascal and Lazarus/it2009-03-31T10:58:25Z<p>Amedeo: /* Campione di sangue */</p>
<hr />
<div>{{Object_Oriented_Programming_with_FreePascal_and_Lazarus}}<br />
<br />
Esistono molte guide eccellenti su Pascal, ma questa guida tenta di coinvolgere ulteriormente il principiante , nella programmazione orientata agli oggetti o [[Glossary#OO | Object-Oriented Programming]], che è un'estensione dello standard pascal, offerta da Turbo pascal, Delphi e FreePascal/Lazarus.<br />
<br />
Un [[Glossary#Object | Object]] è un'estensione della struttura standard pascal detta [http://wiki.lazarus.freepascal.org/Record record]<br />
<br />
La programmazione Pascal in testo standard è adatta alla creazione di applicazioni che, come le applicazioni Unix tradizionali,sono adatte per fare una cosa e per farla molto bene.<br />
<br />
Ciò che un programma fa può essere un'azione veramente complicata ,e può offrire all'utente molte opzioni di menu,<br />
ma è essenzialmente ristretta ad obbedire a comandi che l'utente digita da tastiera e a listare le sue risposte sul terminale o sulla stampante. <br />
<br />
Per poter produrre una [[Glossary#GUI | Graphical User Interface (GUI)]] usualmente si utilizza una sorta di Metodo di programmazione orientata agli oggetti (spesso facendo uso di [[Glossary#C Programming Language | C]] o di una delle sue varianti, o Visual Basic, o una delle [[Glossary#OO | OO]] varianti di Pascal quali [[Glossary#FreePascal | FreePascal]] con o senza [[Glossary#Lazarus | Lazarus]]). <br />
<br />
In una GUI all'utente vengono presentate schermate con un gran numero di immagini organizzate in modo strutturato, consistenti in un'insieme di strumenti o [[Glossary#Widget | Widgets]] che sono associati con varie azioni quali <br />
*selezioni da menu, <br />
*aperture o salvataggio files , <br />
*connessioni ad Internet, <br />
*esecuzioni di calcoli numerici, etc. <br />
<br />
L'utente dovrà muovere il mouse o qualche altro puntatore o strumento sullo schermo, per selezionare le azioni che saranno eseguite in risposta al click del mouse o ai tasti premuti.<br />
<br />
I sistemi per offrire una complessa interfaccia grafica possono essere scritti in Pascal standard o quasi qualsiasi altro linguaggio di programmazione, ma è molto più facile l'utilizzo di un sistema orientato agli oggetti, in cui ogni oggetto grafico sullo schermo può avere tutte le sue proprietà e le sue procedure e funzioni connesse con il suo uso conglobate in una struttura comune.<br />
<br />
<br />
== Oggetti - una analogia con il mondo reale == <br />
Consideriamo le analogie di un campione di sangue prelevato in un ospedale o in uno studio medico.<br />
=== Campione di sangue ===<br />
Il campione fisico è certamente un oggetto o '''object'''; ed ha , associato con esso una quantità di informazioni,documenti ed altri oggetti fisici. <br />
<br />
*'''Provetta''', del tipo determinato dal test che si dovrà eseguire.<br />
<br />
*'''Metodica''' (o ''metodo'', ''procedura operativa standard'') utilizzata dall'infermiera o dal tecnico di laboratorio che prelevano e processano il campione <br />
** che tipo di provetta si dovrà usare, <br />
**come processare il campione<br />
**come conservarlo prima di consegnarlo al laboratorio. <br />
<br />
*'''Etichetta''' sulla provetta con i dettagli per <br />
**identificare il campione <br />
**Nome e cognome e data di nascita del paziente <br />
** data e ora del prelievo <br />
** analisi richieste. <br />
<br />
*'''Modulo di richiesta''' che accompagna il campione per il laboratorio cui il campione è diretto <br />
** ID Campione<br />
**ID del medico richiedente<br />
** quali analisi il medico richiede e <br />
**anamnesi e dettagli completi del paziente<br />
**La possibile diagnosi di cui si richiede conferma. <br />
<br />
<br />
Una copia delle richiesta viene conservata nella cartella clinica per ricordare al medico di attendersi risultati entro un periodo di tempo adeguato. <br />
<br />
<br />
*In laboratorio - '''metodi locali''' per determinare <br />
**come il campione deve essere analizzato, <br />
**Quale strumento usare, <br />
**come lo strumento dovrà operare e come dovrà essere calibrato, <br />
**come il risultato dovrà essere memorizzato formattato e <br />
**presentato al medico. <br />
<br />
L'effettivo'' 'risultato''' è un dato che il medico usa per formulare la diagnosi, e una copia dei risultati è archiviata nella cartella clinica del paziente.<br />
<br />
Il campione fisico può essere conservato per riferimento,per test di conferma o ulteriori test, o potrà essere smaltito in ottemperanza alle norme per lo smaltimento dei campioni biologici o mediante incenerimento, ci sarà un metodo per descrivere questo procedimento.<br />
<br />
<br />
Non è necessario che il medico dica tutti i dettagli operativi e le istruzioni di lavoro ogni qualvolta che un campione viene prelevato; anzi,egli può avere ben poche conoscenze di come il campione verrà processato dal laboratorio. <br />
<br />
I dettagli dei vari processi sono'' '''ereditati''' dai precedenti processi dei campione in analisi ,ossia a priori si è stabilito il metodo di processo del campione - ci sarà un piano generico per l'intera sequenza, e insieme abbiamo potuto pensare al campione di sangue,a tutti i suoi documenti e dati, e la metodica di base, come a un complesso'' 'oggetto'''.<br />
<br />
<br />
<br />
Traduzione da completare.....<br />
<br />
In the physician's mind, the blood sample is seen as almost the same entity as its results, and to the nurses and technicians the sample, the tube, the label and the storage conditions again form a single entity.<br />
<br />
Nella mente del medico, il campione di sangue è visto quasi come la stessa entità, come i suoi risultati, e per gli infermieri e tecnici il campione, la provetta, l'etichetta e le condizioni di conservazione anch'esse come se fossero una sola<br />
<br />
=== Another Example - Automobile ===<br />
If you don't like blood, the same sort of reasoning could be applied to a car taken to a garage for repair.<br />
It might consist of:<br />
*the physical vehicle<br />
*documents held by the owner: registration or license (including license plates), insurance, receipts for purchase, parts, repairs etc<br />
*the fuel consumption history<br />
*the drivers allowed to use the vehicle, with their license particulars<br />
*service records held by the garage<br />
*methods or procedures to be followed for routine checking and maintenance<br />
*methods to be followed for non-routine repairs etc<br />
*billing information for the customer<br />
<br />
== Programming Example ==<br />
<br />
Enough of this pre-occupation with Real-World examples! Let us proceed to the main purpose: programming in FreePascal.<br />
<br />
Let us consider the creation of a simple Form with a few controls for an application in FreePascal/Lazarus.<br />
<br />
<div class="floatleft">[[Image:ObjectInspector-TForm.png]]</div><br />
<div class="floatright">[[Image:BlankForm.png]]</div><br />
<br />
On invoking the Lazarus IDE, the programmer is presented with a blank template Form design, on which he is encouraged to place various controls or objects.<br />
<br />
Note that the pre-made blank Form is already an Object, with its own properties such as position (Top and Left), size (Height and Width), colour, default font for adding text etc.<br />
<br />
<br />
<br />
----<br />
<br />
If a Button control is placed on the Form (type TButton), it will have its own series of properties, which can be examined in the Object Inspector window. <br />
<br />
Several of the properties have names similar to those for the Form; this is because many properties are '''Inherited''' from some common Ancestor class, which lays out how properties are to be defined and handled by the descendant classes. <br />
<br />
As well as properties, the Object Inspector offers a tab called '''Events''', which gives access to Event Handlers which are methods instructing the application how to deal with things such as a mouse click on a button (OnClick) or some change in the position, size or other properties (OnChange).<br />
<br />
The physical image of the Button on the Form, together with all its properties and Event Handler methods, should be regarded as a single entity or '''Object''' in Pascal.<br />
<br />
<div class="floatleft">[[Image:ObjectInspector-TButton.png]]</div><br />
<div class="floatright">[[Image:FormWithButton.png]]</div><br />
<div class="floatright">[[Image:Source_FormWithButton1.png ]]</div><br />
<br />
== Object-Oriented Extensions to standard Pascal ==<br />
<br />
The Pascal record structure is extended by defining an <br />
=== Object ===<br />
<br />
An Object is a special kind of record. The record contains all the fields that<br />
are declared in the object's definition (just like a conventional record), but now procedures and functions can be declared as if they were part of the record and are held as pointers to the methods associated with the object's type. <br />
<br />
For example, an object could contain an array of real values, together with a Method for calculating the average.<br />
<br />
Type<br />
Average = Object<br />
NumVal: Integer;<br />
Values: Array [1..200] of Real;<br />
Function Mean: Real; { calculates the average value of the array }<br />
End;<br />
<br />
Objects can ”inherit” fields and methods from ”parent” objects. This means that these fields and methods can be used as if they were included in the objects declared as a ”child” object.<br />
<br />
Furthermore, a concept of visibility is introduced: fields, procedures and functions can be declared<br />
as public, protected or private. By default, fields and methods are public, and can be exported outside the<br />
current unit. Protected fields or methods are available only to objects descended from the current ancestor object. Fields or methods that are declared private are only accessible in the current unit:<br />
their scope is limited to the implementation of the current unit.<br />
<br />
=== Class ===<br />
Objects are not used very often by themselves in FreePascal and Lazarus; instead, Classes are used very widely. A Class is defined in almost the same way as an Object, but is a pointer to an Object rather than the Object itself. Technically, this means that the Class is allocated on the Heap of a program, whereas the Object is allocated on the Stack.<br />
<br />
Here is a simple example of a typical Class declaration:<br />
{-----------------------------------------}<br />
{example of Class declaration from the LCL}<br />
{-----------------------------------------}<br />
TPen = class(TFPCustomPen)<br />
private<br />
FColor: TColor;<br />
FPenHandleCached: boolean;<br />
FReference: TWSPenReference;<br />
procedure FreeReference;<br />
function GetHandle: HPEN;<br />
function GetReference: TWSPenReference;<br />
procedure ReferenceNeeded;<br />
procedure SetHandle(const Value: HPEN);<br />
protected<br />
procedure DoAllocateResources; override;<br />
procedure DoDeAllocateResources; override;<br />
procedure DoCopyProps(From: TFPCanvasHelper); override;<br />
procedure SetColor<br />
(const NewColor: TColor; const NewFPColor: TFPColor); virtual;<br />
procedure SetFPColor(const AValue: TFPColor); override;<br />
procedure SetColor(Value: TColor);<br />
procedure SetMode(Value: TPenMode); override;<br />
procedure SetStyle(Value: TPenStyle); override;<br />
procedure SetWidth(value: Integer); override;<br />
public<br />
constructor Create; override;<br />
destructor Destroy; override;<br />
procedure Assign(Source: TPersistent); override;<br />
property Handle: HPEN read GetHandle write SetHandle; deprecated;<br />
property Reference: TWSPenReference read GetReference;<br />
published<br />
property Color: TColor read FColor write SetColor default clBlack;<br />
property Mode default pmCopy;<br />
property Style default psSolid;<br />
property Width default 1;<br />
end;<br />
<br />
<br />
Note that this class is defined as an instance of another '''parent''' or '''ancestor''' class (''TFPCustomPen'') from which it '''inherits''' all its properties and methods. It has some fields of its own, grouped under<br />
*'''private''' - this means that items defined here are only available or visible to other classes or procedures/function defined within the same program unit (this example is from ''Graphics'', so any of the other classes such as ''TBitMap'', ''TPicture'' etc in the same unit can use them). They are essentially local variables (eg ''FColor'', ''FPenHandleCached'') or locally used methods (''GetHandle'', ''SetHandle'') but can be used or referred to in items declared in the '''protected''' or '''public''' sections.<br />
*'''protected''' - this means that items defined here are only available or visible to classes that are descended from this '''ancestor''' class, and inherit its properties or methods<br />
*'''public''' - this means that items defined here are available to any programming unit that includes the current unit in its [[Glossary#Uses | Uses]] clause <br />
*'''published''' - is the same as a '''public''' section, but the compiler also generates type information that is needed for automatic streaming of these classes. Often the list of published items appear in the Object Inspector of Lazarus; if there is no '''published''' list, all the '''public''' fields usually appear in the Object Inspector.<br />
<br />
=== Methods ===<br />
A method is just like a standard procedure or function, but can have some additional '''directives'''.<br />
<br />
Some of the methods defined above are labelled with the directive '''virtual'''; others are labelled with the '''override''' directive.<br />
*'''virtual''' means that the type or actual instance of a method is not known at compile-time, but is selected at run-time depending on what sub-program actually calls the method. It could be considered a place-holder in the definition of the class.<br />
*'''override''' means that at run-time the locally given definition can take the place of a definition inherited from an ancestor class, particularly if it was '''virtual'''. If you particularly want to use the method defined in the ancestor class, it is sometimes necessary to call it specifically with the '''inherited''' clause.<br />
<br />
Methods with no virtual or override directive are '''static''' methods (the usual kind in Pascal). Those with a virtual or override directive are '''dynamic'''.<br />
<br />
Special instances of methods are:<br />
*'''create''' - a '''constructor''' for a class, which takes care of allocating memory, collecting together all the information needed and configuring/initializing the various properties.<br />
*'''destroy''' - a '''destructor''' for a class, which removes all the parts of the class from the system in an orderly and logical way, and returns all its resources for the system to re-use.<br />
<br />
=== Properties ===<br />
<br />
Properties are just like ordinary fields in a conventional Pascal record, but they can have '''read''' and/or '''write''' specifiers.<br />
*'''read''' specifier is a field, or a function that returns a result of the correct type for the property. In the example above, the property ''Color'' has a read specifier ''FColor'', which is a local variable containing the value to be used. If a property has a '''read''' but no '''write''' specifier, it is read-only.<br />
*'''write''' specifier is a field, or a procedure that will store the value of the property in a specific location. In the example above, ''Color'' has a write specifier ''SetColor'' that is a procedure (defined in the '''protected''' section) for writing the color value to some specified location. If a property has a '''write''' but no '''read''' specifier, it is write-only.<br />
*'''default''' - note that it is possible to set a '''default''' value for a property. For example, ''Color'' here is given the default value ''clBlack'', or black, at the time of creation. It could subsequently be given a different value, by a programming assignment statement, or in the Object Inspector.<br />
<br />
<br />
== Further information ==<br />
<br />
This has only scratched the surface of the topic. For more details, readers are strongly recommended to read the [http://lazarus-ccr.sourceforge.net/fpcdoc/ref/ref.html FreePascal] manuals, especially Chapters 5 ('''Objects''') and 6 ('''Classes''')<br />
<br />
--[[User:Kirkpatc|Kirkpatc]] 11:04, 20 July 2008 (CEST)<br />
<br />
----<br />
[[Console Mode Pascal]]</div>Amedeohttps://wiki.freepascal.org/index.php?title=Object_Oriented_Programming_with_Free_Pascal_and_Lazarus/it&diff=34743Object Oriented Programming with Free Pascal and Lazarus/it2009-03-31T10:15:46Z<p>Amedeo: /* Campione di sangue */</p>
<hr />
<div>{{Object_Oriented_Programming_with_FreePascal_and_Lazarus}}<br />
<br />
Esistono molte guide eccellenti su Pascal, ma questa guida tenta di coinvolgere ulteriormente il principiante , nella programmazione orientata agli oggetti o [[Glossary#OO | Object-Oriented Programming]], che è un'estensione dello standard pascal, offerta da Turbo pascal, Delphi e FreePascal/Lazarus.<br />
<br />
Un [[Glossary#Object | Object]] è un'estensione della struttura standard pascal detta [http://wiki.lazarus.freepascal.org/Record record]<br />
<br />
La programmazione Pascal in testo standard è adatta alla creazione di applicazioni che, come le applicazioni Unix tradizionali,sono adatte per fare una cosa e per farla molto bene.<br />
<br />
Ciò che un programma fa può essere un'azione veramente complicata ,e può offrire all'utente molte opzioni di menu,<br />
ma è essenzialmente ristretta ad obbedire a comandi che l'utente digita da tastiera e a listare le sue risposte sul terminale o sulla stampante. <br />
<br />
Per poter produrre una [[Glossary#GUI | Graphical User Interface (GUI)]] usualmente si utilizza una sorta di Metodo di programmazione orientata agli oggetti (spesso facendo uso di [[Glossary#C Programming Language | C]] o di una delle sue varianti, o Visual Basic, o una delle [[Glossary#OO | OO]] varianti di Pascal quali [[Glossary#FreePascal | FreePascal]] con o senza [[Glossary#Lazarus | Lazarus]]). <br />
<br />
In una GUI all'utente vengono presentate schermate con un gran numero di immagini organizzate in modo strutturato, consistenti in un'insieme di strumenti o [[Glossary#Widget | Widgets]] che sono associati con varie azioni quali <br />
*selezioni da menu, <br />
*aperture o salvataggio files , <br />
*connessioni ad Internet, <br />
*esecuzioni di calcoli numerici, etc. <br />
<br />
L'utente dovrà muovere il mouse o qualche altro puntatore o strumento sullo schermo, per selezionare le azioni che saranno eseguite in risposta al click del mouse o ai tasti premuti.<br />
<br />
I sistemi per offrire una complessa interfaccia grafica possono essere scritti in Pascal standard o quasi qualsiasi altro linguaggio di programmazione, ma è molto più facile l'utilizzo di un sistema orientato agli oggetti, in cui ogni oggetto grafico sullo schermo può avere tutte le sue proprietà e le sue procedure e funzioni connesse con il suo uso conglobate in una struttura comune.<br />
<br />
<br />
== Oggetti - una analogia con il mondo reale == <br />
Consideriamo le analogie di un campione di sangue prelevato in un ospedale o in uno studio medico.<br />
=== Campione di sangue ===<br />
Il campione fisico è certamente un oggetto o '''object'''; ed ha , associato con esso una quantità di informazioni,documenti ed altri oggetti fisici. <br />
<br />
*'''Provetta''', del tipo determinato dal test che si dovrà eseguire.<br />
<br />
*'''Metodica''' (o ''metodo'', ''procedura operativa standard'') utilizzata dall'infermiera o dal tecnico di laboratorio che prelevano e processano il campione <br />
** che tipo di provetta si dovrà usare, <br />
**come processare il campione<br />
**come conservarlo prima di consegnarlo al laboratorio. <br />
<br />
*'''Etichetta''' sulla provetta con i dettagli per <br />
**identificare il campione <br />
**Nome e cognome e data di nascita del paziente <br />
** data e ora del prelievo <br />
** analisi richieste. <br />
<br />
*'''Modulo di richiesta''' che accompagna il campione per il laboratorio cui il campione è diretto <br />
** ID Campione<br />
**ID del medico richiedente<br />
** quali analisi il medico richiede e <br />
**anamnesi e dettagli completi del paziente<br />
**La possibile diagnosi di cui si richiede conferma. <br />
<br />
<br />
Una copia delle richiesta viene conservata nella cartella clinica per ricordare al medico di attendersi risultati entro un periodo di tempo adeguato. <br />
<br />
<br />
*In laboratorio - '''metodi locali''' per determinare <br />
**come il campione deve essere analizzato, <br />
**Quale strumento usare, <br />
**come lo strumento dovrà operare e come dovrà essere calibrato, <br />
**come il risultato dovrà essere memorizzato formattato e <br />
**presentato al medico. <br />
<br />
L'effettivo'' 'risultato''' è un dato che il medico usa per formulare la diagnosi, e una copia dei risultati è archiviata nella cartella clinica del paziente.<br />
<br />
Il campione fisico può essere conservato per riferimento,per test di conferma o ulteriori test, o potrà essere smaltito in ottemperanza alle norme per lo smaltimento dei campioni biologici o mediante incenerimento, ci sarà un metodo per descrivere questo procedimento.<br />
<br />
<br />
Non è necessario che il medico dica tutti i dettagli operativi e le istruzioni di lavoro ogni qualvolta che un campione viene prelevato; anzi,egli può avere ben poche conoscenze di come il campione verrà processato dal laboratorio. <br />
<br />
I dettagli dei vari processi sono'' '''ereditati''' dai precedenti processi dei campione in analisi ,ossia a priori si è stabilito il metodo di processo del campione - ci sarà un piano generico per l'intera sequenza, e insieme abbiamo potuto pensare al campione di sangue,a tutti i suoi documenti e dati, e la metodica di base, come a un complesso'' 'oggetto'''.<br />
<br />
<br />
<br />
Traduzione da completare.....<br />
<br />
In the physician's mind, the blood sample is seen as almost the same entity as its results, and to the nurses and technicians the sample, the tube, the label and the storage conditions again form a single entity.<br />
<br />
=== Another Example - Automobile ===<br />
If you don't like blood, the same sort of reasoning could be applied to a car taken to a garage for repair.<br />
It might consist of:<br />
*the physical vehicle<br />
*documents held by the owner: registration or license (including license plates), insurance, receipts for purchase, parts, repairs etc<br />
*the fuel consumption history<br />
*the drivers allowed to use the vehicle, with their license particulars<br />
*service records held by the garage<br />
*methods or procedures to be followed for routine checking and maintenance<br />
*methods to be followed for non-routine repairs etc<br />
*billing information for the customer<br />
<br />
== Programming Example ==<br />
<br />
Enough of this pre-occupation with Real-World examples! Let us proceed to the main purpose: programming in FreePascal.<br />
<br />
Let us consider the creation of a simple Form with a few controls for an application in FreePascal/Lazarus.<br />
<br />
<div class="floatleft">[[Image:ObjectInspector-TForm.png]]</div><br />
<div class="floatright">[[Image:BlankForm.png]]</div><br />
<br />
On invoking the Lazarus IDE, the programmer is presented with a blank template Form design, on which he is encouraged to place various controls or objects.<br />
<br />
Note that the pre-made blank Form is already an Object, with its own properties such as position (Top and Left), size (Height and Width), colour, default font for adding text etc.<br />
<br />
<br />
<br />
----<br />
<br />
If a Button control is placed on the Form (type TButton), it will have its own series of properties, which can be examined in the Object Inspector window. <br />
<br />
Several of the properties have names similar to those for the Form; this is because many properties are '''Inherited''' from some common Ancestor class, which lays out how properties are to be defined and handled by the descendant classes. <br />
<br />
As well as properties, the Object Inspector offers a tab called '''Events''', which gives access to Event Handlers which are methods instructing the application how to deal with things such as a mouse click on a button (OnClick) or some change in the position, size or other properties (OnChange).<br />
<br />
The physical image of the Button on the Form, together with all its properties and Event Handler methods, should be regarded as a single entity or '''Object''' in Pascal.<br />
<br />
<div class="floatleft">[[Image:ObjectInspector-TButton.png]]</div><br />
<div class="floatright">[[Image:FormWithButton.png]]</div><br />
<div class="floatright">[[Image:Source_FormWithButton1.png ]]</div><br />
<br />
== Object-Oriented Extensions to standard Pascal ==<br />
<br />
The Pascal record structure is extended by defining an <br />
=== Object ===<br />
<br />
An Object is a special kind of record. The record contains all the fields that<br />
are declared in the object's definition (just like a conventional record), but now procedures and functions can be declared as if they were part of the record and are held as pointers to the methods associated with the object's type. <br />
<br />
For example, an object could contain an array of real values, together with a Method for calculating the average.<br />
<br />
Type<br />
Average = Object<br />
NumVal: Integer;<br />
Values: Array [1..200] of Real;<br />
Function Mean: Real; { calculates the average value of the array }<br />
End;<br />
<br />
Objects can ”inherit” fields and methods from ”parent” objects. This means that these fields and methods can be used as if they were included in the objects declared as a ”child” object.<br />
<br />
Furthermore, a concept of visibility is introduced: fields, procedures and functions can be declared<br />
as public, protected or private. By default, fields and methods are public, and can be exported outside the<br />
current unit. Protected fields or methods are available only to objects descended from the current ancestor object. Fields or methods that are declared private are only accessible in the current unit:<br />
their scope is limited to the implementation of the current unit.<br />
<br />
=== Class ===<br />
Objects are not used very often by themselves in FreePascal and Lazarus; instead, Classes are used very widely. A Class is defined in almost the same way as an Object, but is a pointer to an Object rather than the Object itself. Technically, this means that the Class is allocated on the Heap of a program, whereas the Object is allocated on the Stack.<br />
<br />
Here is a simple example of a typical Class declaration:<br />
{-----------------------------------------}<br />
{example of Class declaration from the LCL}<br />
{-----------------------------------------}<br />
TPen = class(TFPCustomPen)<br />
private<br />
FColor: TColor;<br />
FPenHandleCached: boolean;<br />
FReference: TWSPenReference;<br />
procedure FreeReference;<br />
function GetHandle: HPEN;<br />
function GetReference: TWSPenReference;<br />
procedure ReferenceNeeded;<br />
procedure SetHandle(const Value: HPEN);<br />
protected<br />
procedure DoAllocateResources; override;<br />
procedure DoDeAllocateResources; override;<br />
procedure DoCopyProps(From: TFPCanvasHelper); override;<br />
procedure SetColor<br />
(const NewColor: TColor; const NewFPColor: TFPColor); virtual;<br />
procedure SetFPColor(const AValue: TFPColor); override;<br />
procedure SetColor(Value: TColor);<br />
procedure SetMode(Value: TPenMode); override;<br />
procedure SetStyle(Value: TPenStyle); override;<br />
procedure SetWidth(value: Integer); override;<br />
public<br />
constructor Create; override;<br />
destructor Destroy; override;<br />
procedure Assign(Source: TPersistent); override;<br />
property Handle: HPEN read GetHandle write SetHandle; deprecated;<br />
property Reference: TWSPenReference read GetReference;<br />
published<br />
property Color: TColor read FColor write SetColor default clBlack;<br />
property Mode default pmCopy;<br />
property Style default psSolid;<br />
property Width default 1;<br />
end;<br />
<br />
<br />
Note that this class is defined as an instance of another '''parent''' or '''ancestor''' class (''TFPCustomPen'') from which it '''inherits''' all its properties and methods. It has some fields of its own, grouped under<br />
*'''private''' - this means that items defined here are only available or visible to other classes or procedures/function defined within the same program unit (this example is from ''Graphics'', so any of the other classes such as ''TBitMap'', ''TPicture'' etc in the same unit can use them). They are essentially local variables (eg ''FColor'', ''FPenHandleCached'') or locally used methods (''GetHandle'', ''SetHandle'') but can be used or referred to in items declared in the '''protected''' or '''public''' sections.<br />
*'''protected''' - this means that items defined here are only available or visible to classes that are descended from this '''ancestor''' class, and inherit its properties or methods<br />
*'''public''' - this means that items defined here are available to any programming unit that includes the current unit in its [[Glossary#Uses | Uses]] clause <br />
*'''published''' - is the same as a '''public''' section, but the compiler also generates type information that is needed for automatic streaming of these classes. Often the list of published items appear in the Object Inspector of Lazarus; if there is no '''published''' list, all the '''public''' fields usually appear in the Object Inspector.<br />
<br />
=== Methods ===<br />
A method is just like a standard procedure or function, but can have some additional '''directives'''.<br />
<br />
Some of the methods defined above are labelled with the directive '''virtual'''; others are labelled with the '''override''' directive.<br />
*'''virtual''' means that the type or actual instance of a method is not known at compile-time, but is selected at run-time depending on what sub-program actually calls the method. It could be considered a place-holder in the definition of the class.<br />
*'''override''' means that at run-time the locally given definition can take the place of a definition inherited from an ancestor class, particularly if it was '''virtual'''. If you particularly want to use the method defined in the ancestor class, it is sometimes necessary to call it specifically with the '''inherited''' clause.<br />
<br />
Methods with no virtual or override directive are '''static''' methods (the usual kind in Pascal). Those with a virtual or override directive are '''dynamic'''.<br />
<br />
Special instances of methods are:<br />
*'''create''' - a '''constructor''' for a class, which takes care of allocating memory, collecting together all the information needed and configuring/initializing the various properties.<br />
*'''destroy''' - a '''destructor''' for a class, which removes all the parts of the class from the system in an orderly and logical way, and returns all its resources for the system to re-use.<br />
<br />
=== Properties ===<br />
<br />
Properties are just like ordinary fields in a conventional Pascal record, but they can have '''read''' and/or '''write''' specifiers.<br />
*'''read''' specifier is a field, or a function that returns a result of the correct type for the property. In the example above, the property ''Color'' has a read specifier ''FColor'', which is a local variable containing the value to be used. If a property has a '''read''' but no '''write''' specifier, it is read-only.<br />
*'''write''' specifier is a field, or a procedure that will store the value of the property in a specific location. In the example above, ''Color'' has a write specifier ''SetColor'' that is a procedure (defined in the '''protected''' section) for writing the color value to some specified location. If a property has a '''write''' but no '''read''' specifier, it is write-only.<br />
*'''default''' - note that it is possible to set a '''default''' value for a property. For example, ''Color'' here is given the default value ''clBlack'', or black, at the time of creation. It could subsequently be given a different value, by a programming assignment statement, or in the Object Inspector.<br />
<br />
<br />
== Further information ==<br />
<br />
This has only scratched the surface of the topic. For more details, readers are strongly recommended to read the [http://lazarus-ccr.sourceforge.net/fpcdoc/ref/ref.html FreePascal] manuals, especially Chapters 5 ('''Objects''') and 6 ('''Classes''')<br />
<br />
--[[User:Kirkpatc|Kirkpatc]] 11:04, 20 July 2008 (CEST)<br />
<br />
----<br />
[[Console Mode Pascal]]</div>Amedeohttps://wiki.freepascal.org/index.php?title=Object_Oriented_Programming_with_Free_Pascal_and_Lazarus/it&diff=34740Object Oriented Programming with Free Pascal and Lazarus/it2009-03-31T08:06:44Z<p>Amedeo: /* Campione di sangue */</p>
<hr />
<div>{{Object_Oriented_Programming_with_FreePascal_and_Lazarus}}<br />
<br />
Esistono molte guide eccellenti su Pascal, ma questa guida tenta di coinvolgere ulteriormente il principiante , nella programmazione orientata agli oggetti o [[Glossary#OO | Object-Oriented Programming]], che è un'estensione dello standard pascal, offerta da Turbo pascal, Delphi e FreePascal/Lazarus.<br />
<br />
Un [[Glossary#Object | Object]] è un'estensione della struttura standard pascal detta [http://wiki.lazarus.freepascal.org/Record record]<br />
<br />
La programmazione Pascal in testo standard è adatta alla creazione di applicazioni che, come le applicazioni Unix tradizionali,sono adatte per fare una cosa e per farla molto bene.<br />
<br />
Ciò che un programma fa può essere un'azione veramente complicata ,e può offrire all'utente molte opzioni di menu,<br />
ma è essenzialmente ristretta ad obbedire a comandi che l'utente digita da tastiera e a listare le sue risposte sul terminale o sulla stampante. <br />
<br />
Per poter produrre una [[Glossary#GUI | Graphical User Interface (GUI)]] usualmente si utilizza una sorta di Metodo di programmazione orientata agli oggetti (spesso facendo uso di [[Glossary#C Programming Language | C]] o di una delle sue varianti, o Visual Basic, o una delle [[Glossary#OO | OO]] varianti di Pascal quali [[Glossary#FreePascal | FreePascal]] con o senza [[Glossary#Lazarus | Lazarus]]). <br />
<br />
In una GUI all'utente vengono presentate schermate con un gran numero di immagini organizzate in modo strutturato, consistenti in un'insieme di strumenti o [[Glossary#Widget | Widgets]] che sono associati con varie azioni quali <br />
*selezioni da menu, <br />
*aperture o salvataggio files , <br />
*connessioni ad Internet, <br />
*esecuzioni di calcoli numerici, etc. <br />
<br />
L'utente dovrà muovere il mouse o qualche altro puntatore o strumento sullo schermo, per selezionare le azioni che saranno eseguite in risposta al click del mouse o ai tasti premuti.<br />
<br />
I sistemi per offrire una complessa interfaccia grafica possono essere scritti in Pascal standard o quasi qualsiasi altro linguaggio di programmazione, ma è molto più facile l'utilizzo di un sistema orientato agli oggetti, in cui ogni oggetto grafico sullo schermo può avere tutte le sue proprietà e le sue procedure e funzioni connesse con il suo uso conglobate in una struttura comune.<br />
<br />
<br />
== Oggetti - una analogia con il mondo reale == <br />
Consideriamo le analogie di un campione di sangue prelevato in un ospedale o in uno studio medico.<br />
=== Campione di sangue ===<br />
Il campione fisico è certamente un oggetto o '''object'''; ed ha , associato con esso una quantità di informazioni,documenti ed altri oggetti fisici. <br />
<br />
*'''Provetta''', del tipo determinato dal test che si dovrà eseguire.<br />
<br />
*'''Metodica''' (o ''metodo'', ''procedura operativa standard'') utilizzata dall'infermiera o dal tecnico di laboratorio che prelevano e processano il campione <br />
** che tipo di provetta si dovrà usare, <br />
**come processare il campione<br />
**come conservarlo prima di consegnarlo al laboratorio. <br />
<br />
*'''Etichetta''' sulla provetta con i dettagli per <br />
**identificare il campione <br />
**Nome e cognome e data di nascita del paziente <br />
** data e ora del prelievo <br />
** analisi richieste. <br />
<br />
*'''Modulo di richiesta''' che accompagna il campione per il laboratorio cui il campione è diretto <br />
** ID Campione<br />
**ID del medico richiedente<br />
** quali analisi il medico richiede e <br />
**anamnesi e dettagli completi del paziente<br />
**La possibile diagnosi di cui si richiede conferma. <br />
<br />
<br />
Una copia delle richiesta viene conservata nella cartella clinica per ricordare al medico di attendersi risultati entro un periodo di tempo adeguato. <br />
<br />
<br />
*In laboratorio - '''metodi locali''' per determinare <br />
**come il campione deve essere analizzato, <br />
**Quale strumento usare, <br />
**come lo strumento dovrà operare e come dovrà essere calibrato, <br />
**come il risultato dovrà essere memorizzato formattato e <br />
**presentato al medico. <br />
<br />
L'effettivo'' 'risultato''' è un dato che il medico usa per formulare la diagnosi, e una copia dei risultati è archiviata nella cartella clinica del paziente.<br />
<br />
Il campione fisico può essere conservato per riferimento,per test di conferma o ulteriori test, o potrà essere smaltito in ottemperanza alle norme per lo smaltimento dei campioni biologici o mediante incenerimento, ci sarà un metodo per descrivere questo procedimento.<br />
<br />
<br />
Non è necessario che il medico dica tutti i dettagli operativi e le istruzioni di lavoro ogni qualvolta che un campione viene prelevato; anzi,egli può avere ben poche conoscenze di come il campione verrà processato dal laboratorio. The details of the various processes are '''inherited''' from previous sample collections and analyses - there will be a generic plan for the whole sequence, and together we could think of the blood sample, all its documents and data, and the underlying methods, as a complex '''object'''. <br />
<br />
<br />
Traduzione da completare.....<br />
<br />
In the physician's mind, the blood sample is seen as almost the same entity as its results, and to the nurses and technicians the sample, the tube, the label and the storage conditions again form a single entity.<br />
<br />
=== Another Example - Automobile ===<br />
If you don't like blood, the same sort of reasoning could be applied to a car taken to a garage for repair.<br />
It might consist of:<br />
*the physical vehicle<br />
*documents held by the owner: registration or license (including license plates), insurance, receipts for purchase, parts, repairs etc<br />
*the fuel consumption history<br />
*the drivers allowed to use the vehicle, with their license particulars<br />
*service records held by the garage<br />
*methods or procedures to be followed for routine checking and maintenance<br />
*methods to be followed for non-routine repairs etc<br />
*billing information for the customer<br />
<br />
== Programming Example ==<br />
<br />
Enough of this pre-occupation with Real-World examples! Let us proceed to the main purpose: programming in FreePascal.<br />
<br />
Let us consider the creation of a simple Form with a few controls for an application in FreePascal/Lazarus.<br />
<br />
<div class="floatleft">[[Image:ObjectInspector-TForm.png]]</div><br />
<div class="floatright">[[Image:BlankForm.png]]</div><br />
<br />
On invoking the Lazarus IDE, the programmer is presented with a blank template Form design, on which he is encouraged to place various controls or objects.<br />
<br />
Note that the pre-made blank Form is already an Object, with its own properties such as position (Top and Left), size (Height and Width), colour, default font for adding text etc.<br />
<br />
<br />
<br />
----<br />
<br />
If a Button control is placed on the Form (type TButton), it will have its own series of properties, which can be examined in the Object Inspector window. <br />
<br />
Several of the properties have names similar to those for the Form; this is because many properties are '''Inherited''' from some common Ancestor class, which lays out how properties are to be defined and handled by the descendant classes. <br />
<br />
As well as properties, the Object Inspector offers a tab called '''Events''', which gives access to Event Handlers which are methods instructing the application how to deal with things such as a mouse click on a button (OnClick) or some change in the position, size or other properties (OnChange).<br />
<br />
The physical image of the Button on the Form, together with all its properties and Event Handler methods, should be regarded as a single entity or '''Object''' in Pascal.<br />
<br />
<div class="floatleft">[[Image:ObjectInspector-TButton.png]]</div><br />
<div class="floatright">[[Image:FormWithButton.png]]</div><br />
<div class="floatright">[[Image:Source_FormWithButton1.png ]]</div><br />
<br />
== Object-Oriented Extensions to standard Pascal ==<br />
<br />
The Pascal record structure is extended by defining an <br />
=== Object ===<br />
<br />
An Object is a special kind of record. The record contains all the fields that<br />
are declared in the object's definition (just like a conventional record), but now procedures and functions can be declared as if they were part of the record and are held as pointers to the methods associated with the object's type. <br />
<br />
For example, an object could contain an array of real values, together with a Method for calculating the average.<br />
<br />
Type<br />
Average = Object<br />
NumVal: Integer;<br />
Values: Array [1..200] of Real;<br />
Function Mean: Real; { calculates the average value of the array }<br />
End;<br />
<br />
Objects can ”inherit” fields and methods from ”parent” objects. This means that these fields and methods can be used as if they were included in the objects declared as a ”child” object.<br />
<br />
Furthermore, a concept of visibility is introduced: fields, procedures and functions can be declared<br />
as public, protected or private. By default, fields and methods are public, and can be exported outside the<br />
current unit. Protected fields or methods are available only to objects descended from the current ancestor object. Fields or methods that are declared private are only accessible in the current unit:<br />
their scope is limited to the implementation of the current unit.<br />
<br />
=== Class ===<br />
Objects are not used very often by themselves in FreePascal and Lazarus; instead, Classes are used very widely. A Class is defined in almost the same way as an Object, but is a pointer to an Object rather than the Object itself. Technically, this means that the Class is allocated on the Heap of a program, whereas the Object is allocated on the Stack.<br />
<br />
Here is a simple example of a typical Class declaration:<br />
{-----------------------------------------}<br />
{example of Class declaration from the LCL}<br />
{-----------------------------------------}<br />
TPen = class(TFPCustomPen)<br />
private<br />
FColor: TColor;<br />
FPenHandleCached: boolean;<br />
FReference: TWSPenReference;<br />
procedure FreeReference;<br />
function GetHandle: HPEN;<br />
function GetReference: TWSPenReference;<br />
procedure ReferenceNeeded;<br />
procedure SetHandle(const Value: HPEN);<br />
protected<br />
procedure DoAllocateResources; override;<br />
procedure DoDeAllocateResources; override;<br />
procedure DoCopyProps(From: TFPCanvasHelper); override;<br />
procedure SetColor<br />
(const NewColor: TColor; const NewFPColor: TFPColor); virtual;<br />
procedure SetFPColor(const AValue: TFPColor); override;<br />
procedure SetColor(Value: TColor);<br />
procedure SetMode(Value: TPenMode); override;<br />
procedure SetStyle(Value: TPenStyle); override;<br />
procedure SetWidth(value: Integer); override;<br />
public<br />
constructor Create; override;<br />
destructor Destroy; override;<br />
procedure Assign(Source: TPersistent); override;<br />
property Handle: HPEN read GetHandle write SetHandle; deprecated;<br />
property Reference: TWSPenReference read GetReference;<br />
published<br />
property Color: TColor read FColor write SetColor default clBlack;<br />
property Mode default pmCopy;<br />
property Style default psSolid;<br />
property Width default 1;<br />
end;<br />
<br />
<br />
Note that this class is defined as an instance of another '''parent''' or '''ancestor''' class (''TFPCustomPen'') from which it '''inherits''' all its properties and methods. It has some fields of its own, grouped under<br />
*'''private''' - this means that items defined here are only available or visible to other classes or procedures/function defined within the same program unit (this example is from ''Graphics'', so any of the other classes such as ''TBitMap'', ''TPicture'' etc in the same unit can use them). They are essentially local variables (eg ''FColor'', ''FPenHandleCached'') or locally used methods (''GetHandle'', ''SetHandle'') but can be used or referred to in items declared in the '''protected''' or '''public''' sections.<br />
*'''protected''' - this means that items defined here are only available or visible to classes that are descended from this '''ancestor''' class, and inherit its properties or methods<br />
*'''public''' - this means that items defined here are available to any programming unit that includes the current unit in its [[Glossary#Uses | Uses]] clause <br />
*'''published''' - is the same as a '''public''' section, but the compiler also generates type information that is needed for automatic streaming of these classes. Often the list of published items appear in the Object Inspector of Lazarus; if there is no '''published''' list, all the '''public''' fields usually appear in the Object Inspector.<br />
<br />
=== Methods ===<br />
A method is just like a standard procedure or function, but can have some additional '''directives'''.<br />
<br />
Some of the methods defined above are labelled with the directive '''virtual'''; others are labelled with the '''override''' directive.<br />
*'''virtual''' means that the type or actual instance of a method is not known at compile-time, but is selected at run-time depending on what sub-program actually calls the method. It could be considered a place-holder in the definition of the class.<br />
*'''override''' means that at run-time the locally given definition can take the place of a definition inherited from an ancestor class, particularly if it was '''virtual'''. If you particularly want to use the method defined in the ancestor class, it is sometimes necessary to call it specifically with the '''inherited''' clause.<br />
<br />
Methods with no virtual or override directive are '''static''' methods (the usual kind in Pascal). Those with a virtual or override directive are '''dynamic'''.<br />
<br />
Special instances of methods are:<br />
*'''create''' - a '''constructor''' for a class, which takes care of allocating memory, collecting together all the information needed and configuring/initializing the various properties.<br />
*'''destroy''' - a '''destructor''' for a class, which removes all the parts of the class from the system in an orderly and logical way, and returns all its resources for the system to re-use.<br />
<br />
=== Properties ===<br />
<br />
Properties are just like ordinary fields in a conventional Pascal record, but they can have '''read''' and/or '''write''' specifiers.<br />
*'''read''' specifier is a field, or a function that returns a result of the correct type for the property. In the example above, the property ''Color'' has a read specifier ''FColor'', which is a local variable containing the value to be used. If a property has a '''read''' but no '''write''' specifier, it is read-only.<br />
*'''write''' specifier is a field, or a procedure that will store the value of the property in a specific location. In the example above, ''Color'' has a write specifier ''SetColor'' that is a procedure (defined in the '''protected''' section) for writing the color value to some specified location. If a property has a '''write''' but no '''read''' specifier, it is write-only.<br />
*'''default''' - note that it is possible to set a '''default''' value for a property. For example, ''Color'' here is given the default value ''clBlack'', or black, at the time of creation. It could subsequently be given a different value, by a programming assignment statement, or in the Object Inspector.<br />
<br />
<br />
== Further information ==<br />
<br />
This has only scratched the surface of the topic. For more details, readers are strongly recommended to read the [http://lazarus-ccr.sourceforge.net/fpcdoc/ref/ref.html FreePascal] manuals, especially Chapters 5 ('''Objects''') and 6 ('''Classes''')<br />
<br />
--[[User:Kirkpatc|Kirkpatc]] 11:04, 20 July 2008 (CEST)<br />
<br />
----<br />
[[Console Mode Pascal]]</div>Amedeohttps://wiki.freepascal.org/index.php?title=Object_Oriented_Programming_with_Free_Pascal_and_Lazarus/it&diff=34739Object Oriented Programming with Free Pascal and Lazarus/it2009-03-31T08:00:26Z<p>Amedeo: /* Campione di sangue */</p>
<hr />
<div>{{Object_Oriented_Programming_with_FreePascal_and_Lazarus}}<br />
<br />
Esistono molte guide eccellenti su Pascal, ma questa guida tenta di coinvolgere ulteriormente il principiante , nella programmazione orientata agli oggetti o [[Glossary#OO | Object-Oriented Programming]], che è un'estensione dello standard pascal, offerta da Turbo pascal, Delphi e FreePascal/Lazarus.<br />
<br />
Un [[Glossary#Object | Object]] è un'estensione della struttura standard pascal detta [http://wiki.lazarus.freepascal.org/Record record]<br />
<br />
La programmazione Pascal in testo standard è adatta alla creazione di applicazioni che, come le applicazioni Unix tradizionali,sono adatte per fare una cosa e per farla molto bene.<br />
<br />
Ciò che un programma fa può essere un'azione veramente complicata ,e può offrire all'utente molte opzioni di menu,<br />
ma è essenzialmente ristretta ad obbedire a comandi che l'utente digita da tastiera e a listare le sue risposte sul terminale o sulla stampante. <br />
<br />
Per poter produrre una [[Glossary#GUI | Graphical User Interface (GUI)]] usualmente si utilizza una sorta di Metodo di programmazione orientata agli oggetti (spesso facendo uso di [[Glossary#C Programming Language | C]] o di una delle sue varianti, o Visual Basic, o una delle [[Glossary#OO | OO]] varianti di Pascal quali [[Glossary#FreePascal | FreePascal]] con o senza [[Glossary#Lazarus | Lazarus]]). <br />
<br />
In una GUI all'utente vengono presentate schermate con un gran numero di immagini organizzate in modo strutturato, consistenti in un'insieme di strumenti o [[Glossary#Widget | Widgets]] che sono associati con varie azioni quali <br />
*selezioni da menu, <br />
*aperture o salvataggio files , <br />
*connessioni ad Internet, <br />
*esecuzioni di calcoli numerici, etc. <br />
<br />
L'utente dovrà muovere il mouse o qualche altro puntatore o strumento sullo schermo, per selezionare le azioni che saranno eseguite in risposta al click del mouse o ai tasti premuti.<br />
<br />
I sistemi per offrire una complessa interfaccia grafica possono essere scritti in Pascal standard o quasi qualsiasi altro linguaggio di programmazione, ma è molto più facile l'utilizzo di un sistema orientato agli oggetti, in cui ogni oggetto grafico sullo schermo può avere tutte le sue proprietà e le sue procedure e funzioni connesse con il suo uso conglobate in una struttura comune.<br />
<br />
<br />
== Oggetti - una analogia con il mondo reale == <br />
Consideriamo le analogie di un campione di sangue prelevato in un ospedale o in uno studio medico.<br />
=== Campione di sangue ===<br />
Il campione fisico è certamente un oggetto o '''object'''; ed ha , associato con esso una quantità di informazioni,documenti ed altri oggetti fisici. <br />
<br />
*'''Provetta''', del tipo determinato dal test che si dovrà eseguire.<br />
<br />
*'''Metodica''' (o ''metodo'', ''procedura operativa standard'') utilizzata dall'infermiera o dal tecnico di laboratorio che prelevano e processano il campione <br />
** che tipo di provetta si dovrà usare, <br />
**come processare il campione<br />
**come conservarlo prima di consegnarlo al laboratorio. <br />
<br />
*'''Etichetta''' sulla provetta con i dettagli per <br />
**identificare il campione <br />
**Nome e cognome e data di nascita del paziente <br />
** data e ora del prelievo <br />
** analisi richieste. <br />
<br />
*'''Modulo di richiesta''' che accompagna il campione per il laboratorio cui il campione è diretto <br />
** ID Campione<br />
**ID del medico richiedente<br />
** quali analisi il medico richiede e <br />
**anamnesi e dettagli completi del paziente<br />
**La possibile diagnosi di cui si richiede conferma. <br />
<br />
<br />
Una copia delle richiesta viene conservata nella cartella clinica per ricordare al medico di attendersi risultati entro un periodo di tempo adeguato. <br />
<br />
<br />
*In laboratorio - '''metodi locali''' per determinare <br />
**come il campione deve essere analizzato, <br />
**Quale strumento usare, <br />
**come lo strumento dovrà operare e come dovrà essere calibrato, <br />
**come il risultato dovrà essere memorizzato formattato e <br />
**presentato al medico. <br />
<br />
L'effettivo'' 'risultato''' è un dato che il medico usa per formulare la diagnosi, e una copia dei risultati è archiviata nella cartella clinica del paziente.<br />
<br />
Il campione fisico può essere conservato per riferimento,per test di conferma o ulteriori test, o potrà essere smaltito in ottemperanza alle norme per lo smaltimento dei campioni biologici o mediante incenerimento, ci sarà un metodo per descrivere questo procedimento.<br />
<br />
There is no need for a physician to spell out all the details and instructions every time a sample is collected; indeed, he may have very little knowledge of how the sample is processed in the lab. The details of the various processes are '''inherited''' from previous sample collections and analyses - there will be a generic plan for the whole sequence, and together we could think of the blood sample, all its documents and data, and the underlying methods, as a complex '''object'''. <br />
<br />
<br />
Traduzione da completare.....<br />
<br />
In the physician's mind, the blood sample is seen as almost the same entity as its results, and to the nurses and technicians the sample, the tube, the label and the storage conditions again form a single entity.<br />
<br />
=== Another Example - Automobile ===<br />
If you don't like blood, the same sort of reasoning could be applied to a car taken to a garage for repair.<br />
It might consist of:<br />
*the physical vehicle<br />
*documents held by the owner: registration or license (including license plates), insurance, receipts for purchase, parts, repairs etc<br />
*the fuel consumption history<br />
*the drivers allowed to use the vehicle, with their license particulars<br />
*service records held by the garage<br />
*methods or procedures to be followed for routine checking and maintenance<br />
*methods to be followed for non-routine repairs etc<br />
*billing information for the customer<br />
<br />
== Programming Example ==<br />
<br />
Enough of this pre-occupation with Real-World examples! Let us proceed to the main purpose: programming in FreePascal.<br />
<br />
Let us consider the creation of a simple Form with a few controls for an application in FreePascal/Lazarus.<br />
<br />
<div class="floatleft">[[Image:ObjectInspector-TForm.png]]</div><br />
<div class="floatright">[[Image:BlankForm.png]]</div><br />
<br />
On invoking the Lazarus IDE, the programmer is presented with a blank template Form design, on which he is encouraged to place various controls or objects.<br />
<br />
Note that the pre-made blank Form is already an Object, with its own properties such as position (Top and Left), size (Height and Width), colour, default font for adding text etc.<br />
<br />
<br />
<br />
----<br />
<br />
If a Button control is placed on the Form (type TButton), it will have its own series of properties, which can be examined in the Object Inspector window. <br />
<br />
Several of the properties have names similar to those for the Form; this is because many properties are '''Inherited''' from some common Ancestor class, which lays out how properties are to be defined and handled by the descendant classes. <br />
<br />
As well as properties, the Object Inspector offers a tab called '''Events''', which gives access to Event Handlers which are methods instructing the application how to deal with things such as a mouse click on a button (OnClick) or some change in the position, size or other properties (OnChange).<br />
<br />
The physical image of the Button on the Form, together with all its properties and Event Handler methods, should be regarded as a single entity or '''Object''' in Pascal.<br />
<br />
<div class="floatleft">[[Image:ObjectInspector-TButton.png]]</div><br />
<div class="floatright">[[Image:FormWithButton.png]]</div><br />
<div class="floatright">[[Image:Source_FormWithButton1.png ]]</div><br />
<br />
== Object-Oriented Extensions to standard Pascal ==<br />
<br />
The Pascal record structure is extended by defining an <br />
=== Object ===<br />
<br />
An Object is a special kind of record. The record contains all the fields that<br />
are declared in the object's definition (just like a conventional record), but now procedures and functions can be declared as if they were part of the record and are held as pointers to the methods associated with the object's type. <br />
<br />
For example, an object could contain an array of real values, together with a Method for calculating the average.<br />
<br />
Type<br />
Average = Object<br />
NumVal: Integer;<br />
Values: Array [1..200] of Real;<br />
Function Mean: Real; { calculates the average value of the array }<br />
End;<br />
<br />
Objects can ”inherit” fields and methods from ”parent” objects. This means that these fields and methods can be used as if they were included in the objects declared as a ”child” object.<br />
<br />
Furthermore, a concept of visibility is introduced: fields, procedures and functions can be declared<br />
as public, protected or private. By default, fields and methods are public, and can be exported outside the<br />
current unit. Protected fields or methods are available only to objects descended from the current ancestor object. Fields or methods that are declared private are only accessible in the current unit:<br />
their scope is limited to the implementation of the current unit.<br />
<br />
=== Class ===<br />
Objects are not used very often by themselves in FreePascal and Lazarus; instead, Classes are used very widely. A Class is defined in almost the same way as an Object, but is a pointer to an Object rather than the Object itself. Technically, this means that the Class is allocated on the Heap of a program, whereas the Object is allocated on the Stack.<br />
<br />
Here is a simple example of a typical Class declaration:<br />
{-----------------------------------------}<br />
{example of Class declaration from the LCL}<br />
{-----------------------------------------}<br />
TPen = class(TFPCustomPen)<br />
private<br />
FColor: TColor;<br />
FPenHandleCached: boolean;<br />
FReference: TWSPenReference;<br />
procedure FreeReference;<br />
function GetHandle: HPEN;<br />
function GetReference: TWSPenReference;<br />
procedure ReferenceNeeded;<br />
procedure SetHandle(const Value: HPEN);<br />
protected<br />
procedure DoAllocateResources; override;<br />
procedure DoDeAllocateResources; override;<br />
procedure DoCopyProps(From: TFPCanvasHelper); override;<br />
procedure SetColor<br />
(const NewColor: TColor; const NewFPColor: TFPColor); virtual;<br />
procedure SetFPColor(const AValue: TFPColor); override;<br />
procedure SetColor(Value: TColor);<br />
procedure SetMode(Value: TPenMode); override;<br />
procedure SetStyle(Value: TPenStyle); override;<br />
procedure SetWidth(value: Integer); override;<br />
public<br />
constructor Create; override;<br />
destructor Destroy; override;<br />
procedure Assign(Source: TPersistent); override;<br />
property Handle: HPEN read GetHandle write SetHandle; deprecated;<br />
property Reference: TWSPenReference read GetReference;<br />
published<br />
property Color: TColor read FColor write SetColor default clBlack;<br />
property Mode default pmCopy;<br />
property Style default psSolid;<br />
property Width default 1;<br />
end;<br />
<br />
<br />
Note that this class is defined as an instance of another '''parent''' or '''ancestor''' class (''TFPCustomPen'') from which it '''inherits''' all its properties and methods. It has some fields of its own, grouped under<br />
*'''private''' - this means that items defined here are only available or visible to other classes or procedures/function defined within the same program unit (this example is from ''Graphics'', so any of the other classes such as ''TBitMap'', ''TPicture'' etc in the same unit can use them). They are essentially local variables (eg ''FColor'', ''FPenHandleCached'') or locally used methods (''GetHandle'', ''SetHandle'') but can be used or referred to in items declared in the '''protected''' or '''public''' sections.<br />
*'''protected''' - this means that items defined here are only available or visible to classes that are descended from this '''ancestor''' class, and inherit its properties or methods<br />
*'''public''' - this means that items defined here are available to any programming unit that includes the current unit in its [[Glossary#Uses | Uses]] clause <br />
*'''published''' - is the same as a '''public''' section, but the compiler also generates type information that is needed for automatic streaming of these classes. Often the list of published items appear in the Object Inspector of Lazarus; if there is no '''published''' list, all the '''public''' fields usually appear in the Object Inspector.<br />
<br />
=== Methods ===<br />
A method is just like a standard procedure or function, but can have some additional '''directives'''.<br />
<br />
Some of the methods defined above are labelled with the directive '''virtual'''; others are labelled with the '''override''' directive.<br />
*'''virtual''' means that the type or actual instance of a method is not known at compile-time, but is selected at run-time depending on what sub-program actually calls the method. It could be considered a place-holder in the definition of the class.<br />
*'''override''' means that at run-time the locally given definition can take the place of a definition inherited from an ancestor class, particularly if it was '''virtual'''. If you particularly want to use the method defined in the ancestor class, it is sometimes necessary to call it specifically with the '''inherited''' clause.<br />
<br />
Methods with no virtual or override directive are '''static''' methods (the usual kind in Pascal). Those with a virtual or override directive are '''dynamic'''.<br />
<br />
Special instances of methods are:<br />
*'''create''' - a '''constructor''' for a class, which takes care of allocating memory, collecting together all the information needed and configuring/initializing the various properties.<br />
*'''destroy''' - a '''destructor''' for a class, which removes all the parts of the class from the system in an orderly and logical way, and returns all its resources for the system to re-use.<br />
<br />
=== Properties ===<br />
<br />
Properties are just like ordinary fields in a conventional Pascal record, but they can have '''read''' and/or '''write''' specifiers.<br />
*'''read''' specifier is a field, or a function that returns a result of the correct type for the property. In the example above, the property ''Color'' has a read specifier ''FColor'', which is a local variable containing the value to be used. If a property has a '''read''' but no '''write''' specifier, it is read-only.<br />
*'''write''' specifier is a field, or a procedure that will store the value of the property in a specific location. In the example above, ''Color'' has a write specifier ''SetColor'' that is a procedure (defined in the '''protected''' section) for writing the color value to some specified location. If a property has a '''write''' but no '''read''' specifier, it is write-only.<br />
*'''default''' - note that it is possible to set a '''default''' value for a property. For example, ''Color'' here is given the default value ''clBlack'', or black, at the time of creation. It could subsequently be given a different value, by a programming assignment statement, or in the Object Inspector.<br />
<br />
<br />
== Further information ==<br />
<br />
This has only scratched the surface of the topic. For more details, readers are strongly recommended to read the [http://lazarus-ccr.sourceforge.net/fpcdoc/ref/ref.html FreePascal] manuals, especially Chapters 5 ('''Objects''') and 6 ('''Classes''')<br />
<br />
--[[User:Kirkpatc|Kirkpatc]] 11:04, 20 July 2008 (CEST)<br />
<br />
----<br />
[[Console Mode Pascal]]</div>Amedeohttps://wiki.freepascal.org/index.php?title=Object_Oriented_Programming_with_Free_Pascal_and_Lazarus/it&diff=34738Object Oriented Programming with Free Pascal and Lazarus/it2009-03-31T07:53:48Z<p>Amedeo: /* Campione di sangue */</p>
<hr />
<div>{{Object_Oriented_Programming_with_FreePascal_and_Lazarus}}<br />
<br />
Esistono molte guide eccellenti su Pascal, ma questa guida tenta di coinvolgere ulteriormente il principiante , nella programmazione orientata agli oggetti o [[Glossary#OO | Object-Oriented Programming]], che è un'estensione dello standard pascal, offerta da Turbo pascal, Delphi e FreePascal/Lazarus.<br />
<br />
Un [[Glossary#Object | Object]] è un'estensione della struttura standard pascal detta [http://wiki.lazarus.freepascal.org/Record record]<br />
<br />
La programmazione Pascal in testo standard è adatta alla creazione di applicazioni che, come le applicazioni Unix tradizionali,sono adatte per fare una cosa e per farla molto bene.<br />
<br />
Ciò che un programma fa può essere un'azione veramente complicata ,e può offrire all'utente molte opzioni di menu,<br />
ma è essenzialmente ristretta ad obbedire a comandi che l'utente digita da tastiera e a listare le sue risposte sul terminale o sulla stampante. <br />
<br />
Per poter produrre una [[Glossary#GUI | Graphical User Interface (GUI)]] usualmente si utilizza una sorta di Metodo di programmazione orientata agli oggetti (spesso facendo uso di [[Glossary#C Programming Language | C]] o di una delle sue varianti, o Visual Basic, o una delle [[Glossary#OO | OO]] varianti di Pascal quali [[Glossary#FreePascal | FreePascal]] con o senza [[Glossary#Lazarus | Lazarus]]). <br />
<br />
In una GUI all'utente vengono presentate schermate con un gran numero di immagini organizzate in modo strutturato, consistenti in un'insieme di strumenti o [[Glossary#Widget | Widgets]] che sono associati con varie azioni quali <br />
*selezioni da menu, <br />
*aperture o salvataggio files , <br />
*connessioni ad Internet, <br />
*esecuzioni di calcoli numerici, etc. <br />
<br />
L'utente dovrà muovere il mouse o qualche altro puntatore o strumento sullo schermo, per selezionare le azioni che saranno eseguite in risposta al click del mouse o ai tasti premuti.<br />
<br />
I sistemi per offrire una complessa interfaccia grafica possono essere scritti in Pascal standard o quasi qualsiasi altro linguaggio di programmazione, ma è molto più facile l'utilizzo di un sistema orientato agli oggetti, in cui ogni oggetto grafico sullo schermo può avere tutte le sue proprietà e le sue procedure e funzioni connesse con il suo uso conglobate in una struttura comune.<br />
<br />
<br />
== Oggetti - una analogia con il mondo reale == <br />
Consideriamo le analogie di un campione di sangue prelevato in un ospedale o in uno studio medico.<br />
=== Campione di sangue ===<br />
Il campione fisico è certamente un oggetto o '''object'''; ed ha , associato con esso una quantità di informazioni,documenti ed altri oggetti fisici. <br />
<br />
*'''Provetta''', del tipo determinato dal test che si dovrà eseguire.<br />
<br />
*'''Metodica''' (o ''metodo'', ''procedura operativa standard'') utilizzata dall'infermiera o dal tecnico di laboratorio che prelevano e processano il campione <br />
** che tipo di provetta si dovrà usare, <br />
**come processare il campione<br />
**come conservarlo prima di consegnarlo al laboratorio. <br />
<br />
*'''Etichetta''' sulla provetta con i dettagli per <br />
**identificare il campione <br />
**Nome e cognome e data di nascita del paziente <br />
** data e ora del prelievo <br />
** analisi richieste. <br />
<br />
*'''Modulo di richiesta''' che accompagna il campione per il laboratorio cui il campione è diretto <br />
** ID Campione<br />
**ID del medico richiedente<br />
** quali analisi il medico richiede e <br />
**anamnesi e dettagli completi del paziente<br />
**La possibile diagnosi di cui si richiede conferma. <br />
<br />
<br />
Una copia delle richiesta viene conservata nella cartella clinica per ricordare al medico di attendersi risultati entro un periodo di tempo adeguato. <br />
<br />
<br />
*In laboratorio - '''metodi locali''' per determinare <br />
**come il campione deve essere analizzato, <br />
**Quale strumento usare, <br />
**come lo strumento dovrà operare e come dovrà essere calibrato, <br />
**come il risultato dovrà essere memorizzato formattato e <br />
**presentato al medico. <br />
<br />
Traduzione da completare.....<br />
<br />
The actual '''results''' are a record that the physician uses to assist the diagnosis, and a copy of the results is filed in the patient notes.<br />
<br />
The physical sample might be retained for reference, confirmation or further tests, or might be disposed of by pouring down the sink or by incineration; there will be a method to describe this.<br />
<br />
There is no need for a physician to spell out all the details and instructions every time a sample is collected; indeed, he may have very little knowledge of how the sample is processed in the lab. The details of the various processes are '''inherited''' from previous sample collections and analyses - there will be a generic plan for the whole sequence, and together we could think of the blood sample, all its documents and data, and the underlying methods, as a complex '''object'''. <br />
<br />
In the physician's mind, the blood sample is seen as almost the same entity as its results, and to the nurses and technicians the sample, the tube, the label and the storage conditions again form a single entity.<br />
<br />
=== Another Example - Automobile ===<br />
If you don't like blood, the same sort of reasoning could be applied to a car taken to a garage for repair.<br />
It might consist of:<br />
*the physical vehicle<br />
*documents held by the owner: registration or license (including license plates), insurance, receipts for purchase, parts, repairs etc<br />
*the fuel consumption history<br />
*the drivers allowed to use the vehicle, with their license particulars<br />
*service records held by the garage<br />
*methods or procedures to be followed for routine checking and maintenance<br />
*methods to be followed for non-routine repairs etc<br />
*billing information for the customer<br />
<br />
== Programming Example ==<br />
<br />
Enough of this pre-occupation with Real-World examples! Let us proceed to the main purpose: programming in FreePascal.<br />
<br />
Let us consider the creation of a simple Form with a few controls for an application in FreePascal/Lazarus.<br />
<br />
<div class="floatleft">[[Image:ObjectInspector-TForm.png]]</div><br />
<div class="floatright">[[Image:BlankForm.png]]</div><br />
<br />
On invoking the Lazarus IDE, the programmer is presented with a blank template Form design, on which he is encouraged to place various controls or objects.<br />
<br />
Note that the pre-made blank Form is already an Object, with its own properties such as position (Top and Left), size (Height and Width), colour, default font for adding text etc.<br />
<br />
<br />
<br />
----<br />
<br />
If a Button control is placed on the Form (type TButton), it will have its own series of properties, which can be examined in the Object Inspector window. <br />
<br />
Several of the properties have names similar to those for the Form; this is because many properties are '''Inherited''' from some common Ancestor class, which lays out how properties are to be defined and handled by the descendant classes. <br />
<br />
As well as properties, the Object Inspector offers a tab called '''Events''', which gives access to Event Handlers which are methods instructing the application how to deal with things such as a mouse click on a button (OnClick) or some change in the position, size or other properties (OnChange).<br />
<br />
The physical image of the Button on the Form, together with all its properties and Event Handler methods, should be regarded as a single entity or '''Object''' in Pascal.<br />
<br />
<div class="floatleft">[[Image:ObjectInspector-TButton.png]]</div><br />
<div class="floatright">[[Image:FormWithButton.png]]</div><br />
<div class="floatright">[[Image:Source_FormWithButton1.png ]]</div><br />
<br />
== Object-Oriented Extensions to standard Pascal ==<br />
<br />
The Pascal record structure is extended by defining an <br />
=== Object ===<br />
<br />
An Object is a special kind of record. The record contains all the fields that<br />
are declared in the object's definition (just like a conventional record), but now procedures and functions can be declared as if they were part of the record and are held as pointers to the methods associated with the object's type. <br />
<br />
For example, an object could contain an array of real values, together with a Method for calculating the average.<br />
<br />
Type<br />
Average = Object<br />
NumVal: Integer;<br />
Values: Array [1..200] of Real;<br />
Function Mean: Real; { calculates the average value of the array }<br />
End;<br />
<br />
Objects can ”inherit” fields and methods from ”parent” objects. This means that these fields and methods can be used as if they were included in the objects declared as a ”child” object.<br />
<br />
Furthermore, a concept of visibility is introduced: fields, procedures and functions can be declared<br />
as public, protected or private. By default, fields and methods are public, and can be exported outside the<br />
current unit. Protected fields or methods are available only to objects descended from the current ancestor object. Fields or methods that are declared private are only accessible in the current unit:<br />
their scope is limited to the implementation of the current unit.<br />
<br />
=== Class ===<br />
Objects are not used very often by themselves in FreePascal and Lazarus; instead, Classes are used very widely. A Class is defined in almost the same way as an Object, but is a pointer to an Object rather than the Object itself. Technically, this means that the Class is allocated on the Heap of a program, whereas the Object is allocated on the Stack.<br />
<br />
Here is a simple example of a typical Class declaration:<br />
{-----------------------------------------}<br />
{example of Class declaration from the LCL}<br />
{-----------------------------------------}<br />
TPen = class(TFPCustomPen)<br />
private<br />
FColor: TColor;<br />
FPenHandleCached: boolean;<br />
FReference: TWSPenReference;<br />
procedure FreeReference;<br />
function GetHandle: HPEN;<br />
function GetReference: TWSPenReference;<br />
procedure ReferenceNeeded;<br />
procedure SetHandle(const Value: HPEN);<br />
protected<br />
procedure DoAllocateResources; override;<br />
procedure DoDeAllocateResources; override;<br />
procedure DoCopyProps(From: TFPCanvasHelper); override;<br />
procedure SetColor<br />
(const NewColor: TColor; const NewFPColor: TFPColor); virtual;<br />
procedure SetFPColor(const AValue: TFPColor); override;<br />
procedure SetColor(Value: TColor);<br />
procedure SetMode(Value: TPenMode); override;<br />
procedure SetStyle(Value: TPenStyle); override;<br />
procedure SetWidth(value: Integer); override;<br />
public<br />
constructor Create; override;<br />
destructor Destroy; override;<br />
procedure Assign(Source: TPersistent); override;<br />
property Handle: HPEN read GetHandle write SetHandle; deprecated;<br />
property Reference: TWSPenReference read GetReference;<br />
published<br />
property Color: TColor read FColor write SetColor default clBlack;<br />
property Mode default pmCopy;<br />
property Style default psSolid;<br />
property Width default 1;<br />
end;<br />
<br />
<br />
Note that this class is defined as an instance of another '''parent''' or '''ancestor''' class (''TFPCustomPen'') from which it '''inherits''' all its properties and methods. It has some fields of its own, grouped under<br />
*'''private''' - this means that items defined here are only available or visible to other classes or procedures/function defined within the same program unit (this example is from ''Graphics'', so any of the other classes such as ''TBitMap'', ''TPicture'' etc in the same unit can use them). They are essentially local variables (eg ''FColor'', ''FPenHandleCached'') or locally used methods (''GetHandle'', ''SetHandle'') but can be used or referred to in items declared in the '''protected''' or '''public''' sections.<br />
*'''protected''' - this means that items defined here are only available or visible to classes that are descended from this '''ancestor''' class, and inherit its properties or methods<br />
*'''public''' - this means that items defined here are available to any programming unit that includes the current unit in its [[Glossary#Uses | Uses]] clause <br />
*'''published''' - is the same as a '''public''' section, but the compiler also generates type information that is needed for automatic streaming of these classes. Often the list of published items appear in the Object Inspector of Lazarus; if there is no '''published''' list, all the '''public''' fields usually appear in the Object Inspector.<br />
<br />
=== Methods ===<br />
A method is just like a standard procedure or function, but can have some additional '''directives'''.<br />
<br />
Some of the methods defined above are labelled with the directive '''virtual'''; others are labelled with the '''override''' directive.<br />
*'''virtual''' means that the type or actual instance of a method is not known at compile-time, but is selected at run-time depending on what sub-program actually calls the method. It could be considered a place-holder in the definition of the class.<br />
*'''override''' means that at run-time the locally given definition can take the place of a definition inherited from an ancestor class, particularly if it was '''virtual'''. If you particularly want to use the method defined in the ancestor class, it is sometimes necessary to call it specifically with the '''inherited''' clause.<br />
<br />
Methods with no virtual or override directive are '''static''' methods (the usual kind in Pascal). Those with a virtual or override directive are '''dynamic'''.<br />
<br />
Special instances of methods are:<br />
*'''create''' - a '''constructor''' for a class, which takes care of allocating memory, collecting together all the information needed and configuring/initializing the various properties.<br />
*'''destroy''' - a '''destructor''' for a class, which removes all the parts of the class from the system in an orderly and logical way, and returns all its resources for the system to re-use.<br />
<br />
=== Properties ===<br />
<br />
Properties are just like ordinary fields in a conventional Pascal record, but they can have '''read''' and/or '''write''' specifiers.<br />
*'''read''' specifier is a field, or a function that returns a result of the correct type for the property. In the example above, the property ''Color'' has a read specifier ''FColor'', which is a local variable containing the value to be used. If a property has a '''read''' but no '''write''' specifier, it is read-only.<br />
*'''write''' specifier is a field, or a procedure that will store the value of the property in a specific location. In the example above, ''Color'' has a write specifier ''SetColor'' that is a procedure (defined in the '''protected''' section) for writing the color value to some specified location. If a property has a '''write''' but no '''read''' specifier, it is write-only.<br />
*'''default''' - note that it is possible to set a '''default''' value for a property. For example, ''Color'' here is given the default value ''clBlack'', or black, at the time of creation. It could subsequently be given a different value, by a programming assignment statement, or in the Object Inspector.<br />
<br />
<br />
== Further information ==<br />
<br />
This has only scratched the surface of the topic. For more details, readers are strongly recommended to read the [http://lazarus-ccr.sourceforge.net/fpcdoc/ref/ref.html FreePascal] manuals, especially Chapters 5 ('''Objects''') and 6 ('''Classes''')<br />
<br />
--[[User:Kirkpatc|Kirkpatc]] 11:04, 20 July 2008 (CEST)<br />
<br />
----<br />
[[Console Mode Pascal]]</div>Amedeohttps://wiki.freepascal.org/index.php?title=Object_Oriented_Programming_with_Free_Pascal_and_Lazarus/it&diff=34737Object Oriented Programming with Free Pascal and Lazarus/it2009-03-31T07:52:34Z<p>Amedeo: </p>
<hr />
<div>{{Object_Oriented_Programming_with_FreePascal_and_Lazarus}}<br />
<br />
Esistono molte guide eccellenti su Pascal, ma questa guida tenta di coinvolgere ulteriormente il principiante , nella programmazione orientata agli oggetti o [[Glossary#OO | Object-Oriented Programming]], che è un'estensione dello standard pascal, offerta da Turbo pascal, Delphi e FreePascal/Lazarus.<br />
<br />
Un [[Glossary#Object | Object]] è un'estensione della struttura standard pascal detta [http://wiki.lazarus.freepascal.org/Record record]<br />
<br />
La programmazione Pascal in testo standard è adatta alla creazione di applicazioni che, come le applicazioni Unix tradizionali,sono adatte per fare una cosa e per farla molto bene.<br />
<br />
Ciò che un programma fa può essere un'azione veramente complicata ,e può offrire all'utente molte opzioni di menu,<br />
ma è essenzialmente ristretta ad obbedire a comandi che l'utente digita da tastiera e a listare le sue risposte sul terminale o sulla stampante. <br />
<br />
Per poter produrre una [[Glossary#GUI | Graphical User Interface (GUI)]] usualmente si utilizza una sorta di Metodo di programmazione orientata agli oggetti (spesso facendo uso di [[Glossary#C Programming Language | C]] o di una delle sue varianti, o Visual Basic, o una delle [[Glossary#OO | OO]] varianti di Pascal quali [[Glossary#FreePascal | FreePascal]] con o senza [[Glossary#Lazarus | Lazarus]]). <br />
<br />
In una GUI all'utente vengono presentate schermate con un gran numero di immagini organizzate in modo strutturato, consistenti in un'insieme di strumenti o [[Glossary#Widget | Widgets]] che sono associati con varie azioni quali <br />
*selezioni da menu, <br />
*aperture o salvataggio files , <br />
*connessioni ad Internet, <br />
*esecuzioni di calcoli numerici, etc. <br />
<br />
L'utente dovrà muovere il mouse o qualche altro puntatore o strumento sullo schermo, per selezionare le azioni che saranno eseguite in risposta al click del mouse o ai tasti premuti.<br />
<br />
I sistemi per offrire una complessa interfaccia grafica possono essere scritti in Pascal standard o quasi qualsiasi altro linguaggio di programmazione, ma è molto più facile l'utilizzo di un sistema orientato agli oggetti, in cui ogni oggetto grafico sullo schermo può avere tutte le sue proprietà e le sue procedure e funzioni connesse con il suo uso conglobate in una struttura comune.<br />
<br />
<br />
== Oggetti - una analogia con il mondo reale == <br />
Consideriamo le analogie di un campione di sangue prelevato in un ospedale o in uno studio medico.<br />
=== Campione di sangue ===<br />
Il campione fisico è certamente un oggetto o '''object'''; ed ha , associato con esso una quantità di informazioni,documenti ed altri oggetti fisici. <br />
<br />
*'''Provetta''', del tipo determinato dal test che si dovrà eseguire.<br />
<br />
*'''Metodica''' (o ''metodo'', ''procedura operativa standard'') utilizzata dall'infermiera o dal tecnico di laboratorio che prelevano e processano il campione <br />
** che tipo di provetta si dovrà usare, <br />
**come processare il campione<br />
**come conservarlo prima di consegnarlo al laboratorio. <br />
<br />
*'''Etichetta''' sulla provetta con i dettagli per <br />
**identificare il campione <br />
**Nome e cognome e data di nascita del paziente <br />
** data e ora del prelievo <br />
** analisi richieste. <br />
<br />
*'''Modulo di richiesta''' che accompagna il campione per il laboratorio cui il campione è diretto <br />
** ID Campione<br />
**ID del medico richiedente<br />
** quali analisi il medico richiede e <br />
**anamnesi e dettagli completi del paziente<br />
**La possibile diagnosi di cui si richiede conferma. <br />
<br />
<br />
Una copia delle richiesta viene conservata nella cartella clinica per ricordare al medico di attendersi risultati entro un periodo di tempo adeguato. <br />
<br />
Traduzione da completare.....<br />
<br />
*In laboratorio - '''metodi locali''' per determinare <br />
**come il campione deve essere analizzato, <br />
**Quale strumento usare, <br />
**come lo strumento dovrà operare e come dovrà essere calibrato, <br />
**come il risultato dovrà essere memorizzato formattato e <br />
**presentato al medico. <br />
<br />
The actual '''results''' are a record that the physician uses to assist the diagnosis, and a copy of the results is filed in the patient notes.<br />
<br />
The physical sample might be retained for reference, confirmation or further tests, or might be disposed of by pouring down the sink or by incineration; there will be a method to describe this.<br />
<br />
There is no need for a physician to spell out all the details and instructions every time a sample is collected; indeed, he may have very little knowledge of how the sample is processed in the lab. The details of the various processes are '''inherited''' from previous sample collections and analyses - there will be a generic plan for the whole sequence, and together we could think of the blood sample, all its documents and data, and the underlying methods, as a complex '''object'''. <br />
<br />
In the physician's mind, the blood sample is seen as almost the same entity as its results, and to the nurses and technicians the sample, the tube, the label and the storage conditions again form a single entity.<br />
<br />
=== Another Example - Automobile ===<br />
If you don't like blood, the same sort of reasoning could be applied to a car taken to a garage for repair.<br />
It might consist of:<br />
*the physical vehicle<br />
*documents held by the owner: registration or license (including license plates), insurance, receipts for purchase, parts, repairs etc<br />
*the fuel consumption history<br />
*the drivers allowed to use the vehicle, with their license particulars<br />
*service records held by the garage<br />
*methods or procedures to be followed for routine checking and maintenance<br />
*methods to be followed for non-routine repairs etc<br />
*billing information for the customer<br />
<br />
== Programming Example ==<br />
<br />
Enough of this pre-occupation with Real-World examples! Let us proceed to the main purpose: programming in FreePascal.<br />
<br />
Let us consider the creation of a simple Form with a few controls for an application in FreePascal/Lazarus.<br />
<br />
<div class="floatleft">[[Image:ObjectInspector-TForm.png]]</div><br />
<div class="floatright">[[Image:BlankForm.png]]</div><br />
<br />
On invoking the Lazarus IDE, the programmer is presented with a blank template Form design, on which he is encouraged to place various controls or objects.<br />
<br />
Note that the pre-made blank Form is already an Object, with its own properties such as position (Top and Left), size (Height and Width), colour, default font for adding text etc.<br />
<br />
<br />
<br />
----<br />
<br />
If a Button control is placed on the Form (type TButton), it will have its own series of properties, which can be examined in the Object Inspector window. <br />
<br />
Several of the properties have names similar to those for the Form; this is because many properties are '''Inherited''' from some common Ancestor class, which lays out how properties are to be defined and handled by the descendant classes. <br />
<br />
As well as properties, the Object Inspector offers a tab called '''Events''', which gives access to Event Handlers which are methods instructing the application how to deal with things such as a mouse click on a button (OnClick) or some change in the position, size or other properties (OnChange).<br />
<br />
The physical image of the Button on the Form, together with all its properties and Event Handler methods, should be regarded as a single entity or '''Object''' in Pascal.<br />
<br />
<div class="floatleft">[[Image:ObjectInspector-TButton.png]]</div><br />
<div class="floatright">[[Image:FormWithButton.png]]</div><br />
<div class="floatright">[[Image:Source_FormWithButton1.png ]]</div><br />
<br />
== Object-Oriented Extensions to standard Pascal ==<br />
<br />
The Pascal record structure is extended by defining an <br />
=== Object ===<br />
<br />
An Object is a special kind of record. The record contains all the fields that<br />
are declared in the object's definition (just like a conventional record), but now procedures and functions can be declared as if they were part of the record and are held as pointers to the methods associated with the object's type. <br />
<br />
For example, an object could contain an array of real values, together with a Method for calculating the average.<br />
<br />
Type<br />
Average = Object<br />
NumVal: Integer;<br />
Values: Array [1..200] of Real;<br />
Function Mean: Real; { calculates the average value of the array }<br />
End;<br />
<br />
Objects can ”inherit” fields and methods from ”parent” objects. This means that these fields and methods can be used as if they were included in the objects declared as a ”child” object.<br />
<br />
Furthermore, a concept of visibility is introduced: fields, procedures and functions can be declared<br />
as public, protected or private. By default, fields and methods are public, and can be exported outside the<br />
current unit. Protected fields or methods are available only to objects descended from the current ancestor object. Fields or methods that are declared private are only accessible in the current unit:<br />
their scope is limited to the implementation of the current unit.<br />
<br />
=== Class ===<br />
Objects are not used very often by themselves in FreePascal and Lazarus; instead, Classes are used very widely. A Class is defined in almost the same way as an Object, but is a pointer to an Object rather than the Object itself. Technically, this means that the Class is allocated on the Heap of a program, whereas the Object is allocated on the Stack.<br />
<br />
Here is a simple example of a typical Class declaration:<br />
{-----------------------------------------}<br />
{example of Class declaration from the LCL}<br />
{-----------------------------------------}<br />
TPen = class(TFPCustomPen)<br />
private<br />
FColor: TColor;<br />
FPenHandleCached: boolean;<br />
FReference: TWSPenReference;<br />
procedure FreeReference;<br />
function GetHandle: HPEN;<br />
function GetReference: TWSPenReference;<br />
procedure ReferenceNeeded;<br />
procedure SetHandle(const Value: HPEN);<br />
protected<br />
procedure DoAllocateResources; override;<br />
procedure DoDeAllocateResources; override;<br />
procedure DoCopyProps(From: TFPCanvasHelper); override;<br />
procedure SetColor<br />
(const NewColor: TColor; const NewFPColor: TFPColor); virtual;<br />
procedure SetFPColor(const AValue: TFPColor); override;<br />
procedure SetColor(Value: TColor);<br />
procedure SetMode(Value: TPenMode); override;<br />
procedure SetStyle(Value: TPenStyle); override;<br />
procedure SetWidth(value: Integer); override;<br />
public<br />
constructor Create; override;<br />
destructor Destroy; override;<br />
procedure Assign(Source: TPersistent); override;<br />
property Handle: HPEN read GetHandle write SetHandle; deprecated;<br />
property Reference: TWSPenReference read GetReference;<br />
published<br />
property Color: TColor read FColor write SetColor default clBlack;<br />
property Mode default pmCopy;<br />
property Style default psSolid;<br />
property Width default 1;<br />
end;<br />
<br />
<br />
Note that this class is defined as an instance of another '''parent''' or '''ancestor''' class (''TFPCustomPen'') from which it '''inherits''' all its properties and methods. It has some fields of its own, grouped under<br />
*'''private''' - this means that items defined here are only available or visible to other classes or procedures/function defined within the same program unit (this example is from ''Graphics'', so any of the other classes such as ''TBitMap'', ''TPicture'' etc in the same unit can use them). They are essentially local variables (eg ''FColor'', ''FPenHandleCached'') or locally used methods (''GetHandle'', ''SetHandle'') but can be used or referred to in items declared in the '''protected''' or '''public''' sections.<br />
*'''protected''' - this means that items defined here are only available or visible to classes that are descended from this '''ancestor''' class, and inherit its properties or methods<br />
*'''public''' - this means that items defined here are available to any programming unit that includes the current unit in its [[Glossary#Uses | Uses]] clause <br />
*'''published''' - is the same as a '''public''' section, but the compiler also generates type information that is needed for automatic streaming of these classes. Often the list of published items appear in the Object Inspector of Lazarus; if there is no '''published''' list, all the '''public''' fields usually appear in the Object Inspector.<br />
<br />
=== Methods ===<br />
A method is just like a standard procedure or function, but can have some additional '''directives'''.<br />
<br />
Some of the methods defined above are labelled with the directive '''virtual'''; others are labelled with the '''override''' directive.<br />
*'''virtual''' means that the type or actual instance of a method is not known at compile-time, but is selected at run-time depending on what sub-program actually calls the method. It could be considered a place-holder in the definition of the class.<br />
*'''override''' means that at run-time the locally given definition can take the place of a definition inherited from an ancestor class, particularly if it was '''virtual'''. If you particularly want to use the method defined in the ancestor class, it is sometimes necessary to call it specifically with the '''inherited''' clause.<br />
<br />
Methods with no virtual or override directive are '''static''' methods (the usual kind in Pascal). Those with a virtual or override directive are '''dynamic'''.<br />
<br />
Special instances of methods are:<br />
*'''create''' - a '''constructor''' for a class, which takes care of allocating memory, collecting together all the information needed and configuring/initializing the various properties.<br />
*'''destroy''' - a '''destructor''' for a class, which removes all the parts of the class from the system in an orderly and logical way, and returns all its resources for the system to re-use.<br />
<br />
=== Properties ===<br />
<br />
Properties are just like ordinary fields in a conventional Pascal record, but they can have '''read''' and/or '''write''' specifiers.<br />
*'''read''' specifier is a field, or a function that returns a result of the correct type for the property. In the example above, the property ''Color'' has a read specifier ''FColor'', which is a local variable containing the value to be used. If a property has a '''read''' but no '''write''' specifier, it is read-only.<br />
*'''write''' specifier is a field, or a procedure that will store the value of the property in a specific location. In the example above, ''Color'' has a write specifier ''SetColor'' that is a procedure (defined in the '''protected''' section) for writing the color value to some specified location. If a property has a '''write''' but no '''read''' specifier, it is write-only.<br />
*'''default''' - note that it is possible to set a '''default''' value for a property. For example, ''Color'' here is given the default value ''clBlack'', or black, at the time of creation. It could subsequently be given a different value, by a programming assignment statement, or in the Object Inspector.<br />
<br />
<br />
== Further information ==<br />
<br />
This has only scratched the surface of the topic. For more details, readers are strongly recommended to read the [http://lazarus-ccr.sourceforge.net/fpcdoc/ref/ref.html FreePascal] manuals, especially Chapters 5 ('''Objects''') and 6 ('''Classes''')<br />
<br />
--[[User:Kirkpatc|Kirkpatc]] 11:04, 20 July 2008 (CEST)<br />
<br />
----<br />
[[Console Mode Pascal]]</div>Amedeohttps://wiki.freepascal.org/index.php?title=Object_Oriented_Programming_with_Free_Pascal_and_Lazarus/it&diff=34726Object Oriented Programming with Free Pascal and Lazarus/it2009-03-30T13:07:17Z<p>Amedeo: /* Campione di sangue */</p>
<hr />
<div>{{Programmazione_Orientata_agli_Oggetti_con_FreePascal_e_Lazarus}}<br />
<br />
Esistono molte guide eccellenti su Pascal, ma questa guida tenta di coinvolgere ulteriormente il principiante , nella programmazione orientata agli oggetti o [[Glossary#OO | Object-Oriented Programming]], che è un'estensione dello standard pascal, offerta da Turbo pascal, Delphi e FreePascal/Lazarus.<br />
<br />
Un [[Glossary#Object | Object]] è un'estensione della struttura standard pascal detta [http://wiki.lazarus.freepascal.org/Record record]<br />
<br />
La programmazione Pascal in testo standard è adatta alla creazione di applicazioni che, come le applicazioni Unix tradizionali,sono adatte per fare una cosa e per farla molto bene.<br />
<br />
Ciò che un programma fa può essere un'azione veramente complicata ,e può offrire all'utente molte opzioni di menu,<br />
ma è essenzialmente ristretta ad obbedire a comandi che l'utente digita da tastiera e a listare le sue risposte sul terminale o sulla stampante. <br />
<br />
Per poter produrre una [[Glossary#GUI | Graphical User Interface (GUI)]] usualmente si utilizza una sorta di Metodo di programmazione orientata agli oggetti (spesso facendo uso di [[Glossary#C Programming Language | C]] o di una delle sue varianti, o Visual Basic, o una delle [[Glossary#OO | OO]] varianti di Pascal quali [[Glossary#FreePascal | FreePascal]] con o senza [[Glossary#Lazarus | Lazarus]]). <br />
<br />
In una GUI all'utente vengono presentate schermate con un gran numero di immagini organizzate in modo strutturato, consistenti in un'insieme di strumenti o [[Glossary#Widget | Widgets]] che sono associati con varie azioni quali <br />
*selezioni da menu, <br />
*aperture o salvataggio files , <br />
*connessioni ad Internet, <br />
*esecuzioni di calcoli numerici, etc. <br />
<br />
L'utente dovrà muovere il mouse o qualche altro puntatore o strumento sullo schermo, per selezionare le azioni che saranno eseguite in risposta al click del mouse o ai tasti premuti.<br />
<br />
I sistemi per offrire una complessa interfaccia grafica possono essere scritti in Pascal standard o quasi qualsiasi altro linguaggio di programmazione, ma è molto più facile l'utilizzo di un sistema orientato agli oggetti, in cui ogni oggetto grafico sullo schermo può avere tutte le sue proprietà e le sue procedure e funzioni connesse con il suo uso conglobate in una struttura comune.<br />
<br />
<br />
== Oggetti - una analogia con il mondo reale == <br />
Consideriamo le analogie di un campione di sangue prelevato in un ospedale o in uno studio medico.<br />
=== Campione di sangue ===<br />
Il campione fisico è certamente un oggetto o '''object'''; ed ha , associato con esso una quantità di informazioni,documenti ed altri oggetti fisici. <br />
<br />
*'''Provetta''', del tipo determinato dal test che si dovrà eseguire.<br />
<br />
*'''Metodica''' (o ''metodo'', ''procedura operativa standard'') utilizzata dall'infermiera o dal tecnico di laboratorio che prelevano e processano il campione <br />
** che tipo di provetta si dovrà usare, <br />
**come processare il campione<br />
**come conservarlo prima di consegnarlo al laboratorio. <br />
<br />
*'''Etichetta''' sulla provetta con i dettagli per <br />
**identificare il campione <br />
**Nome e cognome e data di nascita del paziente <br />
** data e ora del prelievo <br />
** analisi richieste. <br />
<br />
*'''Modulo di richiesta''' che accompagna il campione per il laboratorio cui il campione è diretto <br />
** ID Campione<br />
**ID del medico richiedente<br />
** quali analisi il medico richiede e <br />
**anamnesi e dettagli completi del paziente<br />
**La possibile diagnosi di cui si richiede conferma. <br />
<br />
<br />
Una copia delle richiesta viene conservata nella cartella clinica per ricordare al medico di attendersi risultati entro un periodo di tempo adeguato. <br />
<br />
Traduzione da completare.....<br />
<br />
*In the lab - '''local methods''' to determine <br />
**how the sample is to be analysed, <br />
**what machines to use, <br />
**how the machines are to be calibrated and operated, <br />
**how the results are to be stored, formatted and <br />
**reported back to the physician. <br />
<br />
The actual '''results''' are a record that the physician uses to assist the diagnosis, and a copy of the results is filed in the patient notes.<br />
<br />
The physical sample might be retained for reference, confirmation or further tests, or might be disposed of by pouring down the sink or by incineration; there will be a method to describe this.<br />
<br />
There is no need for a physician to spell out all the details and instructions every time a sample is collected; indeed, he may have very little knowledge of how the sample is processed in the lab. The details of the various processes are '''inherited''' from previous sample collections and analyses - there will be a generic plan for the whole sequence, and together we could think of the blood sample, all its documents and data, and the underlying methods, as a complex '''object'''. <br />
<br />
In the physician's mind, the blood sample is seen as almost the same entity as its results, and to the nurses and technicians the sample, the tube, the label and the storage conditions again form a single entity.<br />
<br />
=== Another Example - Automobile ===<br />
If you don't like blood, the same sort of reasoning could be applied to a car taken to a garage for repair.<br />
It might consist of:<br />
*the physical vehicle<br />
*documents held by the owner: registration or license (including license plates), insurance, receipts for purchase, parts, repairs etc<br />
*the fuel consumption history<br />
*the drivers allowed to use the vehicle, with their license particulars<br />
*service records held by the garage<br />
*methods or procedures to be followed for routine checking and maintenance<br />
*methods to be followed for non-routine repairs etc<br />
*billing information for the customer<br />
<br />
== Programming Example ==<br />
<br />
Enough of this pre-occupation with Real-World examples! Let us proceed to the main purpose: programming in FreePascal.<br />
<br />
Let us consider the creation of a simple Form with a few controls for an application in FreePascal/Lazarus.<br />
<br />
<div class="floatleft">[[Image:ObjectInspector-TForm.png]]</div><br />
<div class="floatright">[[Image:BlankForm.png]]</div><br />
<br />
On invoking the Lazarus IDE, the programmer is presented with a blank template Form design, on which he is encouraged to place various controls or objects.<br />
<br />
Note that the pre-made blank Form is already an Object, with its own properties such as position (Top and Left), size (Height and Width), colour, default font for adding text etc.<br />
<br />
<br />
<br />
----<br />
<br />
If a Button control is placed on the Form (type TButton), it will have its own series of properties, which can be examined in the Object Inspector window. <br />
<br />
Several of the properties have names similar to those for the Form; this is because many properties are '''Inherited''' from some common Ancestor class, which lays out how properties are to be defined and handled by the descendant classes. <br />
<br />
As well as properties, the Object Inspector offers a tab called '''Events''', which gives access to Event Handlers which are methods instructing the application how to deal with things such as a mouse click on a button (OnClick) or some change in the position, size or other properties (OnChange).<br />
<br />
The physical image of the Button on the Form, together with all its properties and Event Handler methods, should be regarded as a single entity or '''Object''' in Pascal.<br />
<br />
<div class="floatleft">[[Image:ObjectInspector-TButton.png]]</div><br />
<div class="floatright">[[Image:FormWithButton.png]]</div><br />
<div class="floatright">[[Image:Source_FormWithButton1.png ]]</div><br />
<br />
== Object-Oriented Extensions to standard Pascal ==<br />
<br />
The Pascal record structure is extended by defining an <br />
=== Object ===<br />
<br />
An Object is a special kind of record. The record contains all the fields that<br />
are declared in the object's definition (just like a conventional record), but now procedures and functions can be declared as if they were part of the record and are held as pointers to the methods associated with the object's type. <br />
<br />
For example, an object could contain an array of real values, together with a Method for calculating the average.<br />
<br />
Type<br />
Average = Object<br />
NumVal: Integer;<br />
Values: Array [1..200] of Real;<br />
Function Mean: Real; { calculates the average value of the array }<br />
End;<br />
<br />
Objects can ”inherit” fields and methods from ”parent” objects. This means that these fields and methods can be used as if they were included in the objects declared as a ”child” object.<br />
<br />
Furthermore, a concept of visibility is introduced: fields, procedures and functions can be declared<br />
as public, protected or private. By default, fields and methods are public, and can be exported outside the<br />
current unit. Protected fields or methods are available only to objects descended from the current ancestor object. Fields or methods that are declared private are only accessible in the current unit:<br />
their scope is limited to the implementation of the current unit.<br />
<br />
=== Class ===<br />
Objects are not used very often by themselves in FreePascal and Lazarus; instead, Classes are used very widely. A Class is defined in almost the same way as an Object, but is a pointer to an Object rather than the Object itself. Technically, this means that the Class is allocated on the Heap of a program, whereas the Object is allocated on the Stack.<br />
<br />
Here is a simple example of a typical Class declaration:<br />
{-----------------------------------------}<br />
{example of Class declaration from the LCL}<br />
{-----------------------------------------}<br />
TPen = class(TFPCustomPen)<br />
private<br />
FColor: TColor;<br />
FPenHandleCached: boolean;<br />
FReference: TWSPenReference;<br />
procedure FreeReference;<br />
function GetHandle: HPEN;<br />
function GetReference: TWSPenReference;<br />
procedure ReferenceNeeded;<br />
procedure SetHandle(const Value: HPEN);<br />
protected<br />
procedure DoAllocateResources; override;<br />
procedure DoDeAllocateResources; override;<br />
procedure DoCopyProps(From: TFPCanvasHelper); override;<br />
procedure SetColor<br />
(const NewColor: TColor; const NewFPColor: TFPColor); virtual;<br />
procedure SetFPColor(const AValue: TFPColor); override;<br />
procedure SetColor(Value: TColor);<br />
procedure SetMode(Value: TPenMode); override;<br />
procedure SetStyle(Value: TPenStyle); override;<br />
procedure SetWidth(value: Integer); override;<br />
public<br />
constructor Create; override;<br />
destructor Destroy; override;<br />
procedure Assign(Source: TPersistent); override;<br />
property Handle: HPEN read GetHandle write SetHandle; deprecated;<br />
property Reference: TWSPenReference read GetReference;<br />
published<br />
property Color: TColor read FColor write SetColor default clBlack;<br />
property Mode default pmCopy;<br />
property Style default psSolid;<br />
property Width default 1;<br />
end;<br />
<br />
<br />
Note that this class is defined as an instance of another '''parent''' or '''ancestor''' class (''TFPCustomPen'') from which it '''inherits''' all its properties and methods. It has some fields of its own, grouped under<br />
*'''private''' - this means that items defined here are only available or visible to other classes or procedures/function defined within the same program unit (this example is from ''Graphics'', so any of the other classes such as ''TBitMap'', ''TPicture'' etc in the same unit can use them). They are essentially local variables (eg ''FColor'', ''FPenHandleCached'') or locally used methods (''GetHandle'', ''SetHandle'') but can be used or referred to in items declared in the '''protected''' or '''public''' sections.<br />
*'''protected''' - this means that items defined here are only available or visible to classes that are descended from this '''ancestor''' class, and inherit its properties or methods<br />
*'''public''' - this means that items defined here are available to any programming unit that includes the current unit in its [[Glossary#Uses | Uses]] clause <br />
*'''published''' - is the same as a '''public''' section, but the compiler also generates type information that is needed for automatic streaming of these classes. Often the list of published items appear in the Object Inspector of Lazarus; if there is no '''published''' list, all the '''public''' fields usually appear in the Object Inspector.<br />
<br />
=== Methods ===<br />
A method is just like a standard procedure or function, but can have some additional '''directives'''.<br />
<br />
Some of the methods defined above are labelled with the directive '''virtual'''; others are labelled with the '''override''' directive.<br />
*'''virtual''' means that the type or actual instance of a method is not known at compile-time, but is selected at run-time depending on what sub-program actually calls the method. It could be considered a place-holder in the definition of the class.<br />
*'''override''' means that at run-time the locally given definition can take the place of a definition inherited from an ancestor class, particularly if it was '''virtual'''. If you particularly want to use the method defined in the ancestor class, it is sometimes necessary to call it specifically with the '''inherited''' clause.<br />
<br />
Methods with no virtual or override directive are '''static''' methods (the usual kind in Pascal). Those with a virtual or override directive are '''dynamic'''.<br />
<br />
Special instances of methods are:<br />
*'''create''' - a '''constructor''' for a class, which takes care of allocating memory, collecting together all the information needed and configuring/initializing the various properties.<br />
*'''destroy''' - a '''destructor''' for a class, which removes all the parts of the class from the system in an orderly and logical way, and returns all its resources for the system to re-use.<br />
<br />
=== Properties ===<br />
<br />
Properties are just like ordinary fields in a conventional Pascal record, but they can have '''read''' and/or '''write''' specifiers.<br />
*'''read''' specifier is a field, or a function that returns a result of the correct type for the property. In the example above, the property ''Color'' has a read specifier ''FColor'', which is a local variable containing the value to be used. If a property has a '''read''' but no '''write''' specifier, it is read-only.<br />
*'''write''' specifier is a field, or a procedure that will store the value of the property in a specific location. In the example above, ''Color'' has a write specifier ''SetColor'' that is a procedure (defined in the '''protected''' section) for writing the color value to some specified location. If a property has a '''write''' but no '''read''' specifier, it is write-only.<br />
*'''default''' - note that it is possible to set a '''default''' value for a property. For example, ''Color'' here is given the default value ''clBlack'', or black, at the time of creation. It could subsequently be given a different value, by a programming assignment statement, or in the Object Inspector.<br />
<br />
<br />
== Further information ==<br />
<br />
This has only scratched the surface of the topic. For more details, readers are strongly recommended to read the [http://lazarus-ccr.sourceforge.net/fpcdoc/ref/ref.html FreePascal] manuals, especially Chapters 5 ('''Objects''') and 6 ('''Classes''')<br />
<br />
--[[User:Kirkpatc|Kirkpatc]] 11:04, 20 July 2008 (CEST)<br />
<br />
----<br />
[[Console Mode Pascal]]</div>Amedeohttps://wiki.freepascal.org/index.php?title=Object_Oriented_Programming_with_Free_Pascal_and_Lazarus/it&diff=34725Object Oriented Programming with Free Pascal and Lazarus/it2009-03-30T13:05:27Z<p>Amedeo: </p>
<hr />
<div>{{Programmazione_Orientata_agli_Oggetti_con_FreePascal_e_Lazarus}}<br />
<br />
Esistono molte guide eccellenti su Pascal, ma questa guida tenta di coinvolgere ulteriormente il principiante , nella programmazione orientata agli oggetti o [[Glossary#OO | Object-Oriented Programming]], che è un'estensione dello standard pascal, offerta da Turbo pascal, Delphi e FreePascal/Lazarus.<br />
<br />
Un [[Glossary#Object | Object]] è un'estensione della struttura standard pascal detta [http://wiki.lazarus.freepascal.org/Record record]<br />
<br />
La programmazione Pascal in testo standard è adatta alla creazione di applicazioni che, come le applicazioni Unix tradizionali,sono adatte per fare una cosa e per farla molto bene.<br />
<br />
Ciò che un programma fa può essere un'azione veramente complicata ,e può offrire all'utente molte opzioni di menu,<br />
ma è essenzialmente ristretta ad obbedire a comandi che l'utente digita da tastiera e a listare le sue risposte sul terminale o sulla stampante. <br />
<br />
Per poter produrre una [[Glossary#GUI | Graphical User Interface (GUI)]] usualmente si utilizza una sorta di Metodo di programmazione orientata agli oggetti (spesso facendo uso di [[Glossary#C Programming Language | C]] o di una delle sue varianti, o Visual Basic, o una delle [[Glossary#OO | OO]] varianti di Pascal quali [[Glossary#FreePascal | FreePascal]] con o senza [[Glossary#Lazarus | Lazarus]]). <br />
<br />
In una GUI all'utente vengono presentate schermate con un gran numero di immagini organizzate in modo strutturato, consistenti in un'insieme di strumenti o [[Glossary#Widget | Widgets]] che sono associati con varie azioni quali <br />
*selezioni da menu, <br />
*aperture o salvataggio files , <br />
*connessioni ad Internet, <br />
*esecuzioni di calcoli numerici, etc. <br />
<br />
L'utente dovrà muovere il mouse o qualche altro puntatore o strumento sullo schermo, per selezionare le azioni che saranno eseguite in risposta al click del mouse o ai tasti premuti.<br />
<br />
I sistemi per offrire una complessa interfaccia grafica possono essere scritti in Pascal standard o quasi qualsiasi altro linguaggio di programmazione, ma è molto più facile l'utilizzo di un sistema orientato agli oggetti, in cui ogni oggetto grafico sullo schermo può avere tutte le sue proprietà e le sue procedure e funzioni connesse con il suo uso conglobate in una struttura comune.<br />
<br />
<br />
== Oggetti - una analogia con il mondo reale == <br />
Consideriamo le analogie di un campione di sangue prelevato in un ospedale o in uno studio medico.<br />
=== Campione di sangue ===<br />
Il campione fisico è certamente un oggetto o '''object'''; ed ha , associato con esso una quantità di informazioni,documenti ed altri oggetti fisici. <br />
<br />
*'''Provetta''', del tipo determinato dal test che si dovrà eseguire.<br />
<br />
*'''Metodica''' (o ''metodo'', ''procedura operativa standard'') utilizzata dall'infermiera o dal tecnico di laboratorio che prelevano e processano il campione <br />
** che tipo di provetta si dovrà usare, <br />
**come processare il campione<br />
**come conservarlo prima di consegnarlo al laboratorio. <br />
<br />
*'''Etichetta''' sulla provetta con i dettagli per <br />
**identificare il campione <br />
**Nome e cognome e data di nascita del paziente <br />
** data e ora del prelievo <br />
** analisi richieste. <br />
<br />
*'''Modulo di richiesta''' che accompagna il campione per il laboratorio cui il campione è diretto <br />
** ID Campione<br />
**ID del medico richiedente<br />
** quali analisi il medico richiede e <br />
**anamnesi e dettagli completi del paziente<br />
**La possibile diagnosi di cui si richiede conferma. <br />
<br />
<br />
Una copia delle richiesta viene conservata nella cartella clinica per ricordare al medico di attendersi risultati entro un periodo di tempo adeguato. <br />
<br />
*In the lab - '''local methods''' to determine <br />
**how the sample is to be analysed, <br />
**what machines to use, <br />
**how the machines are to be calibrated and operated, <br />
**how the results are to be stored, formatted and <br />
**reported back to the physician. <br />
<br />
The actual '''results''' are a record that the physician uses to assist the diagnosis, and a copy of the results is filed in the patient notes.<br />
<br />
The physical sample might be retained for reference, confirmation or further tests, or might be disposed of by pouring down the sink or by incineration; there will be a method to describe this.<br />
<br />
There is no need for a physician to spell out all the details and instructions every time a sample is collected; indeed, he may have very little knowledge of how the sample is processed in the lab. The details of the various processes are '''inherited''' from previous sample collections and analyses - there will be a generic plan for the whole sequence, and together we could think of the blood sample, all its documents and data, and the underlying methods, as a complex '''object'''. <br />
<br />
In the physician's mind, the blood sample is seen as almost the same entity as its results, and to the nurses and technicians the sample, the tube, the label and the storage conditions again form a single entity.<br />
=== Another Example - Automobile ===<br />
If you don't like blood, the same sort of reasoning could be applied to a car taken to a garage for repair.<br />
It might consist of:<br />
*the physical vehicle<br />
*documents held by the owner: registration or license (including license plates), insurance, receipts for purchase, parts, repairs etc<br />
*the fuel consumption history<br />
*the drivers allowed to use the vehicle, with their license particulars<br />
*service records held by the garage<br />
*methods or procedures to be followed for routine checking and maintenance<br />
*methods to be followed for non-routine repairs etc<br />
*billing information for the customer<br />
<br />
== Programming Example ==<br />
<br />
Enough of this pre-occupation with Real-World examples! Let us proceed to the main purpose: programming in FreePascal.<br />
<br />
Let us consider the creation of a simple Form with a few controls for an application in FreePascal/Lazarus.<br />
<br />
<div class="floatleft">[[Image:ObjectInspector-TForm.png]]</div><br />
<div class="floatright">[[Image:BlankForm.png]]</div><br />
<br />
On invoking the Lazarus IDE, the programmer is presented with a blank template Form design, on which he is encouraged to place various controls or objects.<br />
<br />
Note that the pre-made blank Form is already an Object, with its own properties such as position (Top and Left), size (Height and Width), colour, default font for adding text etc.<br />
<br />
<br />
<br />
----<br />
<br />
If a Button control is placed on the Form (type TButton), it will have its own series of properties, which can be examined in the Object Inspector window. <br />
<br />
Several of the properties have names similar to those for the Form; this is because many properties are '''Inherited''' from some common Ancestor class, which lays out how properties are to be defined and handled by the descendant classes. <br />
<br />
As well as properties, the Object Inspector offers a tab called '''Events''', which gives access to Event Handlers which are methods instructing the application how to deal with things such as a mouse click on a button (OnClick) or some change in the position, size or other properties (OnChange).<br />
<br />
The physical image of the Button on the Form, together with all its properties and Event Handler methods, should be regarded as a single entity or '''Object''' in Pascal.<br />
<br />
<div class="floatleft">[[Image:ObjectInspector-TButton.png]]</div><br />
<div class="floatright">[[Image:FormWithButton.png]]</div><br />
<div class="floatright">[[Image:Source_FormWithButton1.png ]]</div><br />
<br />
== Object-Oriented Extensions to standard Pascal ==<br />
<br />
The Pascal record structure is extended by defining an <br />
=== Object ===<br />
<br />
An Object is a special kind of record. The record contains all the fields that<br />
are declared in the object's definition (just like a conventional record), but now procedures and functions can be declared as if they were part of the record and are held as pointers to the methods associated with the object's type. <br />
<br />
For example, an object could contain an array of real values, together with a Method for calculating the average.<br />
<br />
Type<br />
Average = Object<br />
NumVal: Integer;<br />
Values: Array [1..200] of Real;<br />
Function Mean: Real; { calculates the average value of the array }<br />
End;<br />
<br />
Objects can ”inherit” fields and methods from ”parent” objects. This means that these fields and methods can be used as if they were included in the objects declared as a ”child” object.<br />
<br />
Furthermore, a concept of visibility is introduced: fields, procedures and functions can be declared<br />
as public, protected or private. By default, fields and methods are public, and can be exported outside the<br />
current unit. Protected fields or methods are available only to objects descended from the current ancestor object. Fields or methods that are declared private are only accessible in the current unit:<br />
their scope is limited to the implementation of the current unit.<br />
<br />
=== Class ===<br />
Objects are not used very often by themselves in FreePascal and Lazarus; instead, Classes are used very widely. A Class is defined in almost the same way as an Object, but is a pointer to an Object rather than the Object itself. Technically, this means that the Class is allocated on the Heap of a program, whereas the Object is allocated on the Stack.<br />
<br />
Here is a simple example of a typical Class declaration:<br />
{-----------------------------------------}<br />
{example of Class declaration from the LCL}<br />
{-----------------------------------------}<br />
TPen = class(TFPCustomPen)<br />
private<br />
FColor: TColor;<br />
FPenHandleCached: boolean;<br />
FReference: TWSPenReference;<br />
procedure FreeReference;<br />
function GetHandle: HPEN;<br />
function GetReference: TWSPenReference;<br />
procedure ReferenceNeeded;<br />
procedure SetHandle(const Value: HPEN);<br />
protected<br />
procedure DoAllocateResources; override;<br />
procedure DoDeAllocateResources; override;<br />
procedure DoCopyProps(From: TFPCanvasHelper); override;<br />
procedure SetColor<br />
(const NewColor: TColor; const NewFPColor: TFPColor); virtual;<br />
procedure SetFPColor(const AValue: TFPColor); override;<br />
procedure SetColor(Value: TColor);<br />
procedure SetMode(Value: TPenMode); override;<br />
procedure SetStyle(Value: TPenStyle); override;<br />
procedure SetWidth(value: Integer); override;<br />
public<br />
constructor Create; override;<br />
destructor Destroy; override;<br />
procedure Assign(Source: TPersistent); override;<br />
property Handle: HPEN read GetHandle write SetHandle; deprecated;<br />
property Reference: TWSPenReference read GetReference;<br />
published<br />
property Color: TColor read FColor write SetColor default clBlack;<br />
property Mode default pmCopy;<br />
property Style default psSolid;<br />
property Width default 1;<br />
end;<br />
<br />
<br />
Note that this class is defined as an instance of another '''parent''' or '''ancestor''' class (''TFPCustomPen'') from which it '''inherits''' all its properties and methods. It has some fields of its own, grouped under<br />
*'''private''' - this means that items defined here are only available or visible to other classes or procedures/function defined within the same program unit (this example is from ''Graphics'', so any of the other classes such as ''TBitMap'', ''TPicture'' etc in the same unit can use them). They are essentially local variables (eg ''FColor'', ''FPenHandleCached'') or locally used methods (''GetHandle'', ''SetHandle'') but can be used or referred to in items declared in the '''protected''' or '''public''' sections.<br />
*'''protected''' - this means that items defined here are only available or visible to classes that are descended from this '''ancestor''' class, and inherit its properties or methods<br />
*'''public''' - this means that items defined here are available to any programming unit that includes the current unit in its [[Glossary#Uses | Uses]] clause <br />
*'''published''' - is the same as a '''public''' section, but the compiler also generates type information that is needed for automatic streaming of these classes. Often the list of published items appear in the Object Inspector of Lazarus; if there is no '''published''' list, all the '''public''' fields usually appear in the Object Inspector.<br />
<br />
=== Methods ===<br />
A method is just like a standard procedure or function, but can have some additional '''directives'''.<br />
<br />
Some of the methods defined above are labelled with the directive '''virtual'''; others are labelled with the '''override''' directive.<br />
*'''virtual''' means that the type or actual instance of a method is not known at compile-time, but is selected at run-time depending on what sub-program actually calls the method. It could be considered a place-holder in the definition of the class.<br />
*'''override''' means that at run-time the locally given definition can take the place of a definition inherited from an ancestor class, particularly if it was '''virtual'''. If you particularly want to use the method defined in the ancestor class, it is sometimes necessary to call it specifically with the '''inherited''' clause.<br />
<br />
Methods with no virtual or override directive are '''static''' methods (the usual kind in Pascal). Those with a virtual or override directive are '''dynamic'''.<br />
<br />
Special instances of methods are:<br />
*'''create''' - a '''constructor''' for a class, which takes care of allocating memory, collecting together all the information needed and configuring/initializing the various properties.<br />
*'''destroy''' - a '''destructor''' for a class, which removes all the parts of the class from the system in an orderly and logical way, and returns all its resources for the system to re-use.<br />
<br />
=== Properties ===<br />
<br />
Properties are just like ordinary fields in a conventional Pascal record, but they can have '''read''' and/or '''write''' specifiers.<br />
*'''read''' specifier is a field, or a function that returns a result of the correct type for the property. In the example above, the property ''Color'' has a read specifier ''FColor'', which is a local variable containing the value to be used. If a property has a '''read''' but no '''write''' specifier, it is read-only.<br />
*'''write''' specifier is a field, or a procedure that will store the value of the property in a specific location. In the example above, ''Color'' has a write specifier ''SetColor'' that is a procedure (defined in the '''protected''' section) for writing the color value to some specified location. If a property has a '''write''' but no '''read''' specifier, it is write-only.<br />
*'''default''' - note that it is possible to set a '''default''' value for a property. For example, ''Color'' here is given the default value ''clBlack'', or black, at the time of creation. It could subsequently be given a different value, by a programming assignment statement, or in the Object Inspector.<br />
<br />
<br />
== Further information ==<br />
<br />
This has only scratched the surface of the topic. For more details, readers are strongly recommended to read the [http://lazarus-ccr.sourceforge.net/fpcdoc/ref/ref.html FreePascal] manuals, especially Chapters 5 ('''Objects''') and 6 ('''Classes''')<br />
<br />
--[[User:Kirkpatc|Kirkpatc]] 11:04, 20 July 2008 (CEST)<br />
<br />
----<br />
[[Console Mode Pascal]]</div>Amedeohttps://wiki.freepascal.org/index.php?title=Object_Oriented_Programming_with_Free_Pascal_and_Lazarus/it&diff=34724Object Oriented Programming with Free Pascal and Lazarus/it2009-03-30T12:30:17Z<p>Amedeo: </p>
<hr />
<div>{{Programmazione_Orientata_agli_Oggetti_con_FreePascal_e_Lazarus}}<br />
<br />
Esistono molte guide eccellenti su Pascal, ma questa guida tenta di coinvolgere ulteriormente il principiante , nella programmazione orientata agli oggetti o [[Glossary#OO | Object-Oriented Programming]], che è un'estensione dello standard pascal, offerta da Turbo pascal, Delphi e FreePascal/Lazarus.<br />
<br />
Un [[Glossary#Object | Object]] è un'estensione della struttura standard pascal detta [http://wiki.lazarus.freepascal.org/Record record]<br />
<br />
La programmazione Pascal in testo standard è adatta alla creazione di applicazioni che, come le applicazioni Unix tradizionali,sono adatte per fare una cosa e per farla molto bene.<br />
<br />
Ciò che un programma fa può essere un'azione veramente complicata ,e può offrire all'utente molte opzioni di menu,<br />
ma è essenzialmente ristretta ad obbedire a comandi che l'utente digita da tastiera e a listare le sue risposte sul terminale o sulla stampante. <br />
<br />
Per poter produrre una [[Glossary#GUI | Graphical User Interface (GUI)]] usualmente si utilizza una sorta di Metodo di programmazione orientata agli oggetti (spesso facendo uso di [[Glossary#C Programming Language | C]] o di una delle sue varianti, o Visual Basic, o una delle [[Glossary#OO | OO]] varianti di Pascal quali [[Glossary#FreePascal | FreePascal]] con o senza [[Glossary#Lazarus | Lazarus]]). <br />
<br />
In una GUI all'utente vengono presentate schermate con un gran numero di immagini organizzate in modo strutturato, consistenti in un'insieme di strumenti o [[Glossary#Widget | Widgets]] che sono associati con varie azioni quali <br />
*selezioni da menu, <br />
*aperture o salvataggio files , <br />
*connessioni ad Internet, <br />
*esecuzioni di calcoli numerici, etc. <br />
<br />
L'utente dovrà muovere il mouse o qualche altro puntatore o strumento sullo schermo, per selezionare le azioni che saranno eseguite in risposta al click del mouse o ai tasti premuti.<br />
<br />
<br />
While systems to deal with a complex graphical user interface could be written in standard Pascal or almost any other programming language, it is much easier to use an object-oriented system, in which each graphical object on the screen can have all its properties and the procedures and functions associated with its use kept together in a common structure.<br />
<br />
<br />
== Objects - a real-world analogy == <br />
Consider the analogy of a blood sample collected in a hospital or a doctor's office.<br />
=== Blood Sample ===<br />
The physical sample is certainly an '''object'''; it has, associated with it, a lot of information, documents and other physical objects. <br />
<br />
*'''Sample tube''', of a type determined by the test that the physician wants performed.<br />
<br />
*'''Local rule''' (or ''method'', ''standard operating procedure'') to direct the nurse or technician collecting the sample <br />
**which type of tube to use, <br />
**how to process the sample <br />
**how to store it before transfer to the lab. <br />
<br />
*'''Label''' on the tube with details of the <br />
**sample identifier<br />
**patient's name and birthdate<br />
**date and time of collection <br />
**tests required. <br />
<br />
*'''Request form''' that accompanies the sample to the lab, directing <br />
**sample ID<br />
**ID of requesting physician<br />
**what test the physician requests and <br />
**giving fuller details of the patient<br />
**the possible diagnosis for which confirmation is sought. <br />
<br />
A copy of the request form is placed in the patient's notes, to remind the physician to expect results within an appropriate time. <br />
<br />
*In the lab - '''local methods''' to determine <br />
**how the sample is to be analysed, <br />
**what machines to use, <br />
**how the machines are to be calibrated and operated, <br />
**how the results are to be stored, formatted and <br />
**reported back to the physician. <br />
<br />
The actual '''results''' are a record that the physician uses to assist the diagnosis, and a copy of the results is filed in the patient notes.<br />
<br />
The physical sample might be retained for reference, confirmation or further tests, or might be disposed of by pouring down the sink or by incineration; there will be a method to describe this.<br />
<br />
There is no need for a physician to spell out all the details and instructions every time a sample is collected; indeed, he may have very little knowledge of how the sample is processed in the lab. The details of the various processes are '''inherited''' from previous sample collections and analyses - there will be a generic plan for the whole sequence, and together we could think of the blood sample, all its documents and data, and the underlying methods, as a complex '''object'''. <br />
<br />
In the physician's mind, the blood sample is seen as almost the same entity as its results, and to the nurses and technicians the sample, the tube, the label and the storage conditions again form a single entity.<br />
=== Another Example - Automobile ===<br />
If you don't like blood, the same sort of reasoning could be applied to a car taken to a garage for repair.<br />
It might consist of:<br />
*the physical vehicle<br />
*documents held by the owner: registration or license (including license plates), insurance, receipts for purchase, parts, repairs etc<br />
*the fuel consumption history<br />
*the drivers allowed to use the vehicle, with their license particulars<br />
*service records held by the garage<br />
*methods or procedures to be followed for routine checking and maintenance<br />
*methods to be followed for non-routine repairs etc<br />
*billing information for the customer<br />
<br />
== Programming Example ==<br />
<br />
Enough of this pre-occupation with Real-World examples! Let us proceed to the main purpose: programming in FreePascal.<br />
<br />
Let us consider the creation of a simple Form with a few controls for an application in FreePascal/Lazarus.<br />
<br />
<div class="floatleft">[[Image:ObjectInspector-TForm.png]]</div><br />
<div class="floatright">[[Image:BlankForm.png]]</div><br />
<br />
On invoking the Lazarus IDE, the programmer is presented with a blank template Form design, on which he is encouraged to place various controls or objects.<br />
<br />
Note that the pre-made blank Form is already an Object, with its own properties such as position (Top and Left), size (Height and Width), colour, default font for adding text etc.<br />
<br />
<br />
<br />
----<br />
<br />
If a Button control is placed on the Form (type TButton), it will have its own series of properties, which can be examined in the Object Inspector window. <br />
<br />
Several of the properties have names similar to those for the Form; this is because many properties are '''Inherited''' from some common Ancestor class, which lays out how properties are to be defined and handled by the descendant classes. <br />
<br />
As well as properties, the Object Inspector offers a tab called '''Events''', which gives access to Event Handlers which are methods instructing the application how to deal with things such as a mouse click on a button (OnClick) or some change in the position, size or other properties (OnChange).<br />
<br />
The physical image of the Button on the Form, together with all its properties and Event Handler methods, should be regarded as a single entity or '''Object''' in Pascal.<br />
<br />
<div class="floatleft">[[Image:ObjectInspector-TButton.png]]</div><br />
<div class="floatright">[[Image:FormWithButton.png]]</div><br />
<div class="floatright">[[Image:Source_FormWithButton1.png ]]</div><br />
<br />
== Object-Oriented Extensions to standard Pascal ==<br />
<br />
The Pascal record structure is extended by defining an <br />
=== Object ===<br />
<br />
An Object is a special kind of record. The record contains all the fields that<br />
are declared in the object's definition (just like a conventional record), but now procedures and functions can be declared as if they were part of the record and are held as pointers to the methods associated with the object's type. <br />
<br />
For example, an object could contain an array of real values, together with a Method for calculating the average.<br />
<br />
Type<br />
Average = Object<br />
NumVal: Integer;<br />
Values: Array [1..200] of Real;<br />
Function Mean: Real; { calculates the average value of the array }<br />
End;<br />
<br />
Objects can ”inherit” fields and methods from ”parent” objects. This means that these fields and methods can be used as if they were included in the objects declared as a ”child” object.<br />
<br />
Furthermore, a concept of visibility is introduced: fields, procedures and functions can be declared<br />
as public, protected or private. By default, fields and methods are public, and can be exported outside the<br />
current unit. Protected fields or methods are available only to objects descended from the current ancestor object. Fields or methods that are declared private are only accessible in the current unit:<br />
their scope is limited to the implementation of the current unit.<br />
<br />
=== Class ===<br />
Objects are not used very often by themselves in FreePascal and Lazarus; instead, Classes are used very widely. A Class is defined in almost the same way as an Object, but is a pointer to an Object rather than the Object itself. Technically, this means that the Class is allocated on the Heap of a program, whereas the Object is allocated on the Stack.<br />
<br />
Here is a simple example of a typical Class declaration:<br />
{-----------------------------------------}<br />
{example of Class declaration from the LCL}<br />
{-----------------------------------------}<br />
TPen = class(TFPCustomPen)<br />
private<br />
FColor: TColor;<br />
FPenHandleCached: boolean;<br />
FReference: TWSPenReference;<br />
procedure FreeReference;<br />
function GetHandle: HPEN;<br />
function GetReference: TWSPenReference;<br />
procedure ReferenceNeeded;<br />
procedure SetHandle(const Value: HPEN);<br />
protected<br />
procedure DoAllocateResources; override;<br />
procedure DoDeAllocateResources; override;<br />
procedure DoCopyProps(From: TFPCanvasHelper); override;<br />
procedure SetColor<br />
(const NewColor: TColor; const NewFPColor: TFPColor); virtual;<br />
procedure SetFPColor(const AValue: TFPColor); override;<br />
procedure SetColor(Value: TColor);<br />
procedure SetMode(Value: TPenMode); override;<br />
procedure SetStyle(Value: TPenStyle); override;<br />
procedure SetWidth(value: Integer); override;<br />
public<br />
constructor Create; override;<br />
destructor Destroy; override;<br />
procedure Assign(Source: TPersistent); override;<br />
property Handle: HPEN read GetHandle write SetHandle; deprecated;<br />
property Reference: TWSPenReference read GetReference;<br />
published<br />
property Color: TColor read FColor write SetColor default clBlack;<br />
property Mode default pmCopy;<br />
property Style default psSolid;<br />
property Width default 1;<br />
end;<br />
<br />
<br />
Note that this class is defined as an instance of another '''parent''' or '''ancestor''' class (''TFPCustomPen'') from which it '''inherits''' all its properties and methods. It has some fields of its own, grouped under<br />
*'''private''' - this means that items defined here are only available or visible to other classes or procedures/function defined within the same program unit (this example is from ''Graphics'', so any of the other classes such as ''TBitMap'', ''TPicture'' etc in the same unit can use them). They are essentially local variables (eg ''FColor'', ''FPenHandleCached'') or locally used methods (''GetHandle'', ''SetHandle'') but can be used or referred to in items declared in the '''protected''' or '''public''' sections.<br />
*'''protected''' - this means that items defined here are only available or visible to classes that are descended from this '''ancestor''' class, and inherit its properties or methods<br />
*'''public''' - this means that items defined here are available to any programming unit that includes the current unit in its [[Glossary#Uses | Uses]] clause <br />
*'''published''' - is the same as a '''public''' section, but the compiler also generates type information that is needed for automatic streaming of these classes. Often the list of published items appear in the Object Inspector of Lazarus; if there is no '''published''' list, all the '''public''' fields usually appear in the Object Inspector.<br />
<br />
=== Methods ===<br />
A method is just like a standard procedure or function, but can have some additional '''directives'''.<br />
<br />
Some of the methods defined above are labelled with the directive '''virtual'''; others are labelled with the '''override''' directive.<br />
*'''virtual''' means that the type or actual instance of a method is not known at compile-time, but is selected at run-time depending on what sub-program actually calls the method. It could be considered a place-holder in the definition of the class.<br />
*'''override''' means that at run-time the locally given definition can take the place of a definition inherited from an ancestor class, particularly if it was '''virtual'''. If you particularly want to use the method defined in the ancestor class, it is sometimes necessary to call it specifically with the '''inherited''' clause.<br />
<br />
Methods with no virtual or override directive are '''static''' methods (the usual kind in Pascal). Those with a virtual or override directive are '''dynamic'''.<br />
<br />
Special instances of methods are:<br />
*'''create''' - a '''constructor''' for a class, which takes care of allocating memory, collecting together all the information needed and configuring/initializing the various properties.<br />
*'''destroy''' - a '''destructor''' for a class, which removes all the parts of the class from the system in an orderly and logical way, and returns all its resources for the system to re-use.<br />
<br />
=== Properties ===<br />
<br />
Properties are just like ordinary fields in a conventional Pascal record, but they can have '''read''' and/or '''write''' specifiers.<br />
*'''read''' specifier is a field, or a function that returns a result of the correct type for the property. In the example above, the property ''Color'' has a read specifier ''FColor'', which is a local variable containing the value to be used. If a property has a '''read''' but no '''write''' specifier, it is read-only.<br />
*'''write''' specifier is a field, or a procedure that will store the value of the property in a specific location. In the example above, ''Color'' has a write specifier ''SetColor'' that is a procedure (defined in the '''protected''' section) for writing the color value to some specified location. If a property has a '''write''' but no '''read''' specifier, it is write-only.<br />
*'''default''' - note that it is possible to set a '''default''' value for a property. For example, ''Color'' here is given the default value ''clBlack'', or black, at the time of creation. It could subsequently be given a different value, by a programming assignment statement, or in the Object Inspector.<br />
<br />
<br />
== Further information ==<br />
<br />
This has only scratched the surface of the topic. For more details, readers are strongly recommended to read the [http://lazarus-ccr.sourceforge.net/fpcdoc/ref/ref.html FreePascal] manuals, especially Chapters 5 ('''Objects''') and 6 ('''Classes''')<br />
<br />
--[[User:Kirkpatc|Kirkpatc]] 11:04, 20 July 2008 (CEST)<br />
<br />
----<br />
[[Console Mode Pascal]]</div>Amedeohttps://wiki.freepascal.org/index.php?title=Object_Oriented_Programming_with_Free_Pascal_and_Lazarus/it&diff=34723Object Oriented Programming with Free Pascal and Lazarus/it2009-03-30T12:23:01Z<p>Amedeo: </p>
<hr />
<div>{{Programmazione_Orientata_agli_Oggetti_con_FreePascal_e_Lazarus}}<br />
<br />
Esistono molte guide eccellenti su Pascal, ma questa guida tenta di coinvolgere il principiante ulteriormente, in [[Glossary#OO | Object-Oriented Programming]], che è un'estensione dello standard pascal, offerta da Turbo pascal, Delphi e FreePascal/Lazarus.<br />
<br />
Un [[Glossary#Object | Object]] è un'estensione della struttura standard pascal [http://wiki.lazarus.freepascal.org/Record record]<br />
<br />
La programmazione Pascal in testo standard è adatta alla creazione di applicazioni che, come le applicazioni Unix tradizionali,sono adatte per fare una cosa e per farla molto bene.<br />
<br />
Ciò che un programma fa può essere un'azione veramente complicata ,e può offrire all'utente molte opzioni di menu,<br />
ma è essenzialmente ristretta ad obbedire a comandi che l'utente digita da tastiera e a listare le sue risposte sul terminale o sulla stampante. <br />
<br />
Per poter produrre una [[Glossary#GUI | Graphical User Interface (GUI)]] usualmente si utilizza una sorta di Metodo di programmazione orientata agli oggetti (spesso facendo uso di [[Glossary#C Programming Language | C]] o di una delle sue varianti, o Visual Basic, o una delle [[Glossary#OO | OO]] varianti di Pascal quali [[Glossary#FreePascal | FreePascal]] con o senza [[Glossary#Lazarus | Lazarus]]). <br />
<br />
In una GUI all'utente vengono presentate schermate con un gran numero di immagini organizzate in modo strutturato, consistenti in un'insieme di strumenti o [[Glossary#Widget | Widgets]] che sono associati con varie azioni quali <br />
*selezioni da menu, <br />
*aperture o salvataggio files , <br />
*connessioni ad Internet, <br />
*esecuzioni di calcoli numerici, etc. <br />
<br />
The user is expected to move a mouse or other pointer/selection tool over the screen, to select actions which are to be performed in response to a mouse button click or a key-press.<br />
<br />
While systems to deal with a complex graphical user interface could be written in standard Pascal or almost any other programming language, it is much easier to use an object-oriented system, in which each graphical object on the screen can have all its properties and the procedures and functions associated with its use kept together in a common structure.<br />
<br />
<br />
== Objects - a real-world analogy == <br />
Consider the analogy of a blood sample collected in a hospital or a doctor's office.<br />
=== Blood Sample ===<br />
The physical sample is certainly an '''object'''; it has, associated with it, a lot of information, documents and other physical objects. <br />
<br />
*'''Sample tube''', of a type determined by the test that the physician wants performed.<br />
<br />
*'''Local rule''' (or ''method'', ''standard operating procedure'') to direct the nurse or technician collecting the sample <br />
**which type of tube to use, <br />
**how to process the sample <br />
**how to store it before transfer to the lab. <br />
<br />
*'''Label''' on the tube with details of the <br />
**sample identifier<br />
**patient's name and birthdate<br />
**date and time of collection <br />
**tests required. <br />
<br />
*'''Request form''' that accompanies the sample to the lab, directing <br />
**sample ID<br />
**ID of requesting physician<br />
**what test the physician requests and <br />
**giving fuller details of the patient<br />
**the possible diagnosis for which confirmation is sought. <br />
<br />
A copy of the request form is placed in the patient's notes, to remind the physician to expect results within an appropriate time. <br />
<br />
*In the lab - '''local methods''' to determine <br />
**how the sample is to be analysed, <br />
**what machines to use, <br />
**how the machines are to be calibrated and operated, <br />
**how the results are to be stored, formatted and <br />
**reported back to the physician. <br />
<br />
The actual '''results''' are a record that the physician uses to assist the diagnosis, and a copy of the results is filed in the patient notes.<br />
<br />
The physical sample might be retained for reference, confirmation or further tests, or might be disposed of by pouring down the sink or by incineration; there will be a method to describe this.<br />
<br />
There is no need for a physician to spell out all the details and instructions every time a sample is collected; indeed, he may have very little knowledge of how the sample is processed in the lab. The details of the various processes are '''inherited''' from previous sample collections and analyses - there will be a generic plan for the whole sequence, and together we could think of the blood sample, all its documents and data, and the underlying methods, as a complex '''object'''. <br />
<br />
In the physician's mind, the blood sample is seen as almost the same entity as its results, and to the nurses and technicians the sample, the tube, the label and the storage conditions again form a single entity.<br />
=== Another Example - Automobile ===<br />
If you don't like blood, the same sort of reasoning could be applied to a car taken to a garage for repair.<br />
It might consist of:<br />
*the physical vehicle<br />
*documents held by the owner: registration or license (including license plates), insurance, receipts for purchase, parts, repairs etc<br />
*the fuel consumption history<br />
*the drivers allowed to use the vehicle, with their license particulars<br />
*service records held by the garage<br />
*methods or procedures to be followed for routine checking and maintenance<br />
*methods to be followed for non-routine repairs etc<br />
*billing information for the customer<br />
<br />
== Programming Example ==<br />
<br />
Enough of this pre-occupation with Real-World examples! Let us proceed to the main purpose: programming in FreePascal.<br />
<br />
Let us consider the creation of a simple Form with a few controls for an application in FreePascal/Lazarus.<br />
<br />
<div class="floatleft">[[Image:ObjectInspector-TForm.png]]</div><br />
<div class="floatright">[[Image:BlankForm.png]]</div><br />
<br />
On invoking the Lazarus IDE, the programmer is presented with a blank template Form design, on which he is encouraged to place various controls or objects.<br />
<br />
Note that the pre-made blank Form is already an Object, with its own properties such as position (Top and Left), size (Height and Width), colour, default font for adding text etc.<br />
<br />
<br />
<br />
----<br />
<br />
If a Button control is placed on the Form (type TButton), it will have its own series of properties, which can be examined in the Object Inspector window. <br />
<br />
Several of the properties have names similar to those for the Form; this is because many properties are '''Inherited''' from some common Ancestor class, which lays out how properties are to be defined and handled by the descendant classes. <br />
<br />
As well as properties, the Object Inspector offers a tab called '''Events''', which gives access to Event Handlers which are methods instructing the application how to deal with things such as a mouse click on a button (OnClick) or some change in the position, size or other properties (OnChange).<br />
<br />
The physical image of the Button on the Form, together with all its properties and Event Handler methods, should be regarded as a single entity or '''Object''' in Pascal.<br />
<br />
<div class="floatleft">[[Image:ObjectInspector-TButton.png]]</div><br />
<div class="floatright">[[Image:FormWithButton.png]]</div><br />
<div class="floatright">[[Image:Source_FormWithButton1.png ]]</div><br />
<br />
== Object-Oriented Extensions to standard Pascal ==<br />
<br />
The Pascal record structure is extended by defining an <br />
=== Object ===<br />
<br />
An Object is a special kind of record. The record contains all the fields that<br />
are declared in the object's definition (just like a conventional record), but now procedures and functions can be declared as if they were part of the record and are held as pointers to the methods associated with the object's type. <br />
<br />
For example, an object could contain an array of real values, together with a Method for calculating the average.<br />
<br />
Type<br />
Average = Object<br />
NumVal: Integer;<br />
Values: Array [1..200] of Real;<br />
Function Mean: Real; { calculates the average value of the array }<br />
End;<br />
<br />
Objects can ”inherit” fields and methods from ”parent” objects. This means that these fields and methods can be used as if they were included in the objects declared as a ”child” object.<br />
<br />
Furthermore, a concept of visibility is introduced: fields, procedures and functions can be declared<br />
as public, protected or private. By default, fields and methods are public, and can be exported outside the<br />
current unit. Protected fields or methods are available only to objects descended from the current ancestor object. Fields or methods that are declared private are only accessible in the current unit:<br />
their scope is limited to the implementation of the current unit.<br />
<br />
=== Class ===<br />
Objects are not used very often by themselves in FreePascal and Lazarus; instead, Classes are used very widely. A Class is defined in almost the same way as an Object, but is a pointer to an Object rather than the Object itself. Technically, this means that the Class is allocated on the Heap of a program, whereas the Object is allocated on the Stack.<br />
<br />
Here is a simple example of a typical Class declaration:<br />
{-----------------------------------------}<br />
{example of Class declaration from the LCL}<br />
{-----------------------------------------}<br />
TPen = class(TFPCustomPen)<br />
private<br />
FColor: TColor;<br />
FPenHandleCached: boolean;<br />
FReference: TWSPenReference;<br />
procedure FreeReference;<br />
function GetHandle: HPEN;<br />
function GetReference: TWSPenReference;<br />
procedure ReferenceNeeded;<br />
procedure SetHandle(const Value: HPEN);<br />
protected<br />
procedure DoAllocateResources; override;<br />
procedure DoDeAllocateResources; override;<br />
procedure DoCopyProps(From: TFPCanvasHelper); override;<br />
procedure SetColor<br />
(const NewColor: TColor; const NewFPColor: TFPColor); virtual;<br />
procedure SetFPColor(const AValue: TFPColor); override;<br />
procedure SetColor(Value: TColor);<br />
procedure SetMode(Value: TPenMode); override;<br />
procedure SetStyle(Value: TPenStyle); override;<br />
procedure SetWidth(value: Integer); override;<br />
public<br />
constructor Create; override;<br />
destructor Destroy; override;<br />
procedure Assign(Source: TPersistent); override;<br />
property Handle: HPEN read GetHandle write SetHandle; deprecated;<br />
property Reference: TWSPenReference read GetReference;<br />
published<br />
property Color: TColor read FColor write SetColor default clBlack;<br />
property Mode default pmCopy;<br />
property Style default psSolid;<br />
property Width default 1;<br />
end;<br />
<br />
<br />
Note that this class is defined as an instance of another '''parent''' or '''ancestor''' class (''TFPCustomPen'') from which it '''inherits''' all its properties and methods. It has some fields of its own, grouped under<br />
*'''private''' - this means that items defined here are only available or visible to other classes or procedures/function defined within the same program unit (this example is from ''Graphics'', so any of the other classes such as ''TBitMap'', ''TPicture'' etc in the same unit can use them). They are essentially local variables (eg ''FColor'', ''FPenHandleCached'') or locally used methods (''GetHandle'', ''SetHandle'') but can be used or referred to in items declared in the '''protected''' or '''public''' sections.<br />
*'''protected''' - this means that items defined here are only available or visible to classes that are descended from this '''ancestor''' class, and inherit its properties or methods<br />
*'''public''' - this means that items defined here are available to any programming unit that includes the current unit in its [[Glossary#Uses | Uses]] clause <br />
*'''published''' - is the same as a '''public''' section, but the compiler also generates type information that is needed for automatic streaming of these classes. Often the list of published items appear in the Object Inspector of Lazarus; if there is no '''published''' list, all the '''public''' fields usually appear in the Object Inspector.<br />
<br />
=== Methods ===<br />
A method is just like a standard procedure or function, but can have some additional '''directives'''.<br />
<br />
Some of the methods defined above are labelled with the directive '''virtual'''; others are labelled with the '''override''' directive.<br />
*'''virtual''' means that the type or actual instance of a method is not known at compile-time, but is selected at run-time depending on what sub-program actually calls the method. It could be considered a place-holder in the definition of the class.<br />
*'''override''' means that at run-time the locally given definition can take the place of a definition inherited from an ancestor class, particularly if it was '''virtual'''. If you particularly want to use the method defined in the ancestor class, it is sometimes necessary to call it specifically with the '''inherited''' clause.<br />
<br />
Methods with no virtual or override directive are '''static''' methods (the usual kind in Pascal). Those with a virtual or override directive are '''dynamic'''.<br />
<br />
Special instances of methods are:<br />
*'''create''' - a '''constructor''' for a class, which takes care of allocating memory, collecting together all the information needed and configuring/initializing the various properties.<br />
*'''destroy''' - a '''destructor''' for a class, which removes all the parts of the class from the system in an orderly and logical way, and returns all its resources for the system to re-use.<br />
<br />
=== Properties ===<br />
<br />
Properties are just like ordinary fields in a conventional Pascal record, but they can have '''read''' and/or '''write''' specifiers.<br />
*'''read''' specifier is a field, or a function that returns a result of the correct type for the property. In the example above, the property ''Color'' has a read specifier ''FColor'', which is a local variable containing the value to be used. If a property has a '''read''' but no '''write''' specifier, it is read-only.<br />
*'''write''' specifier is a field, or a procedure that will store the value of the property in a specific location. In the example above, ''Color'' has a write specifier ''SetColor'' that is a procedure (defined in the '''protected''' section) for writing the color value to some specified location. If a property has a '''write''' but no '''read''' specifier, it is write-only.<br />
*'''default''' - note that it is possible to set a '''default''' value for a property. For example, ''Color'' here is given the default value ''clBlack'', or black, at the time of creation. It could subsequently be given a different value, by a programming assignment statement, or in the Object Inspector.<br />
<br />
<br />
== Further information ==<br />
<br />
This has only scratched the surface of the topic. For more details, readers are strongly recommended to read the [http://lazarus-ccr.sourceforge.net/fpcdoc/ref/ref.html FreePascal] manuals, especially Chapters 5 ('''Objects''') and 6 ('''Classes''')<br />
<br />
--[[User:Kirkpatc|Kirkpatc]] 11:04, 20 July 2008 (CEST)<br />
<br />
----<br />
[[Console Mode Pascal]]</div>Amedeohttps://wiki.freepascal.org/index.php?title=Object_Oriented_Programming_with_Free_Pascal_and_Lazarus/it&diff=34722Object Oriented Programming with Free Pascal and Lazarus/it2009-03-30T12:14:12Z<p>Amedeo: </p>
<hr />
<div>{{Programmazione_Orientata_agli_Oggetti_con_FreePascal_e_Lazarus}}<br />
<br />
Esistono molte guide eccellenti su Pascal, ma questa guida tenta di coinvolgere il principiante ulteriormente, in [[Glossary#OO | Object-Oriented Programming]], che è un'estensione dello standard pascal, offerta da Turbo pascal, Delphi e FreePascal/Lazarus.<br />
<br />
Un [[Glossary#Object | Object]] è un'estensione della struttura standard pascal [http://wiki.lazarus.freepascal.org/Record record]<br />
<br />
La programmazione Pascal in testo standard è adatta alla creazione di applicazioni che, come le applicazioni Unix tradizionali,sono adatte per fare una cosa e per farla molto bene.<br />
<br />
Ciò che un programma fa può essere un'azione veramente complicata ,e può offrire all'utente molte opzioni di menu,<br />
ma è essenzialmente ristretta ad obbedire a comandi che l'utente digita da tastiera e a listare le sue risposte sul terminale o sulla stampante. <br />
<br />
In order to provide a [[Glossary#GUI | Graphical User Interface (GUI)]] it is usual to invoke some sort of Object-Oriented Programming method (often making use of [[Glossary#C Programming Language | C]] or one of its variants, or Visual Basic, or one of the [[Glossary#OO | OO]] variants of Pascal such as [[Glossary#FreePascal | FreePascal]] with or without [[Glossary#Lazarus | Lazarus]]). <br />
<br />
In a GUI the user is presented with a screen with a large number of images arranged in a structured way, consisting of a set of tools or [[Glossary#Widget | Widgets]] that are associated with various actions such as <br />
*selecting from a menu, <br />
*opening or saving files, <br />
*connecting to the Internet, <br />
*performing numerical computations, etc. <br />
<br />
The user is expected to move a mouse or other pointer/selection tool over the screen, to select actions which are to be performed in response to a mouse button click or a key-press.<br />
<br />
While systems to deal with a complex graphical user interface could be written in standard Pascal or almost any other programming language, it is much easier to use an object-oriented system, in which each graphical object on the screen can have all its properties and the procedures and functions associated with its use kept together in a common structure.<br />
<br />
<br />
== Objects - a real-world analogy == <br />
Consider the analogy of a blood sample collected in a hospital or a doctor's office.<br />
=== Blood Sample ===<br />
The physical sample is certainly an '''object'''; it has, associated with it, a lot of information, documents and other physical objects. <br />
<br />
*'''Sample tube''', of a type determined by the test that the physician wants performed.<br />
<br />
*'''Local rule''' (or ''method'', ''standard operating procedure'') to direct the nurse or technician collecting the sample <br />
**which type of tube to use, <br />
**how to process the sample <br />
**how to store it before transfer to the lab. <br />
<br />
*'''Label''' on the tube with details of the <br />
**sample identifier<br />
**patient's name and birthdate<br />
**date and time of collection <br />
**tests required. <br />
<br />
*'''Request form''' that accompanies the sample to the lab, directing <br />
**sample ID<br />
**ID of requesting physician<br />
**what test the physician requests and <br />
**giving fuller details of the patient<br />
**the possible diagnosis for which confirmation is sought. <br />
<br />
A copy of the request form is placed in the patient's notes, to remind the physician to expect results within an appropriate time. <br />
<br />
*In the lab - '''local methods''' to determine <br />
**how the sample is to be analysed, <br />
**what machines to use, <br />
**how the machines are to be calibrated and operated, <br />
**how the results are to be stored, formatted and <br />
**reported back to the physician. <br />
<br />
The actual '''results''' are a record that the physician uses to assist the diagnosis, and a copy of the results is filed in the patient notes.<br />
<br />
The physical sample might be retained for reference, confirmation or further tests, or might be disposed of by pouring down the sink or by incineration; there will be a method to describe this.<br />
<br />
There is no need for a physician to spell out all the details and instructions every time a sample is collected; indeed, he may have very little knowledge of how the sample is processed in the lab. The details of the various processes are '''inherited''' from previous sample collections and analyses - there will be a generic plan for the whole sequence, and together we could think of the blood sample, all its documents and data, and the underlying methods, as a complex '''object'''. <br />
<br />
In the physician's mind, the blood sample is seen as almost the same entity as its results, and to the nurses and technicians the sample, the tube, the label and the storage conditions again form a single entity.<br />
=== Another Example - Automobile ===<br />
If you don't like blood, the same sort of reasoning could be applied to a car taken to a garage for repair.<br />
It might consist of:<br />
*the physical vehicle<br />
*documents held by the owner: registration or license (including license plates), insurance, receipts for purchase, parts, repairs etc<br />
*the fuel consumption history<br />
*the drivers allowed to use the vehicle, with their license particulars<br />
*service records held by the garage<br />
*methods or procedures to be followed for routine checking and maintenance<br />
*methods to be followed for non-routine repairs etc<br />
*billing information for the customer<br />
<br />
== Programming Example ==<br />
<br />
Enough of this pre-occupation with Real-World examples! Let us proceed to the main purpose: programming in FreePascal.<br />
<br />
Let us consider the creation of a simple Form with a few controls for an application in FreePascal/Lazarus.<br />
<br />
<div class="floatleft">[[Image:ObjectInspector-TForm.png]]</div><br />
<div class="floatright">[[Image:BlankForm.png]]</div><br />
<br />
On invoking the Lazarus IDE, the programmer is presented with a blank template Form design, on which he is encouraged to place various controls or objects.<br />
<br />
Note that the pre-made blank Form is already an Object, with its own properties such as position (Top and Left), size (Height and Width), colour, default font for adding text etc.<br />
<br />
<br />
<br />
----<br />
<br />
If a Button control is placed on the Form (type TButton), it will have its own series of properties, which can be examined in the Object Inspector window. <br />
<br />
Several of the properties have names similar to those for the Form; this is because many properties are '''Inherited''' from some common Ancestor class, which lays out how properties are to be defined and handled by the descendant classes. <br />
<br />
As well as properties, the Object Inspector offers a tab called '''Events''', which gives access to Event Handlers which are methods instructing the application how to deal with things such as a mouse click on a button (OnClick) or some change in the position, size or other properties (OnChange).<br />
<br />
The physical image of the Button on the Form, together with all its properties and Event Handler methods, should be regarded as a single entity or '''Object''' in Pascal.<br />
<br />
<div class="floatleft">[[Image:ObjectInspector-TButton.png]]</div><br />
<div class="floatright">[[Image:FormWithButton.png]]</div><br />
<div class="floatright">[[Image:Source_FormWithButton1.png ]]</div><br />
<br />
== Object-Oriented Extensions to standard Pascal ==<br />
<br />
The Pascal record structure is extended by defining an <br />
=== Object ===<br />
<br />
An Object is a special kind of record. The record contains all the fields that<br />
are declared in the object's definition (just like a conventional record), but now procedures and functions can be declared as if they were part of the record and are held as pointers to the methods associated with the object's type. <br />
<br />
For example, an object could contain an array of real values, together with a Method for calculating the average.<br />
<br />
Type<br />
Average = Object<br />
NumVal: Integer;<br />
Values: Array [1..200] of Real;<br />
Function Mean: Real; { calculates the average value of the array }<br />
End;<br />
<br />
Objects can ”inherit” fields and methods from ”parent” objects. This means that these fields and methods can be used as if they were included in the objects declared as a ”child” object.<br />
<br />
Furthermore, a concept of visibility is introduced: fields, procedures and functions can be declared<br />
as public, protected or private. By default, fields and methods are public, and can be exported outside the<br />
current unit. Protected fields or methods are available only to objects descended from the current ancestor object. Fields or methods that are declared private are only accessible in the current unit:<br />
their scope is limited to the implementation of the current unit.<br />
<br />
=== Class ===<br />
Objects are not used very often by themselves in FreePascal and Lazarus; instead, Classes are used very widely. A Class is defined in almost the same way as an Object, but is a pointer to an Object rather than the Object itself. Technically, this means that the Class is allocated on the Heap of a program, whereas the Object is allocated on the Stack.<br />
<br />
Here is a simple example of a typical Class declaration:<br />
{-----------------------------------------}<br />
{example of Class declaration from the LCL}<br />
{-----------------------------------------}<br />
TPen = class(TFPCustomPen)<br />
private<br />
FColor: TColor;<br />
FPenHandleCached: boolean;<br />
FReference: TWSPenReference;<br />
procedure FreeReference;<br />
function GetHandle: HPEN;<br />
function GetReference: TWSPenReference;<br />
procedure ReferenceNeeded;<br />
procedure SetHandle(const Value: HPEN);<br />
protected<br />
procedure DoAllocateResources; override;<br />
procedure DoDeAllocateResources; override;<br />
procedure DoCopyProps(From: TFPCanvasHelper); override;<br />
procedure SetColor<br />
(const NewColor: TColor; const NewFPColor: TFPColor); virtual;<br />
procedure SetFPColor(const AValue: TFPColor); override;<br />
procedure SetColor(Value: TColor);<br />
procedure SetMode(Value: TPenMode); override;<br />
procedure SetStyle(Value: TPenStyle); override;<br />
procedure SetWidth(value: Integer); override;<br />
public<br />
constructor Create; override;<br />
destructor Destroy; override;<br />
procedure Assign(Source: TPersistent); override;<br />
property Handle: HPEN read GetHandle write SetHandle; deprecated;<br />
property Reference: TWSPenReference read GetReference;<br />
published<br />
property Color: TColor read FColor write SetColor default clBlack;<br />
property Mode default pmCopy;<br />
property Style default psSolid;<br />
property Width default 1;<br />
end;<br />
<br />
<br />
Note that this class is defined as an instance of another '''parent''' or '''ancestor''' class (''TFPCustomPen'') from which it '''inherits''' all its properties and methods. It has some fields of its own, grouped under<br />
*'''private''' - this means that items defined here are only available or visible to other classes or procedures/function defined within the same program unit (this example is from ''Graphics'', so any of the other classes such as ''TBitMap'', ''TPicture'' etc in the same unit can use them). They are essentially local variables (eg ''FColor'', ''FPenHandleCached'') or locally used methods (''GetHandle'', ''SetHandle'') but can be used or referred to in items declared in the '''protected''' or '''public''' sections.<br />
*'''protected''' - this means that items defined here are only available or visible to classes that are descended from this '''ancestor''' class, and inherit its properties or methods<br />
*'''public''' - this means that items defined here are available to any programming unit that includes the current unit in its [[Glossary#Uses | Uses]] clause <br />
*'''published''' - is the same as a '''public''' section, but the compiler also generates type information that is needed for automatic streaming of these classes. Often the list of published items appear in the Object Inspector of Lazarus; if there is no '''published''' list, all the '''public''' fields usually appear in the Object Inspector.<br />
<br />
=== Methods ===<br />
A method is just like a standard procedure or function, but can have some additional '''directives'''.<br />
<br />
Some of the methods defined above are labelled with the directive '''virtual'''; others are labelled with the '''override''' directive.<br />
*'''virtual''' means that the type or actual instance of a method is not known at compile-time, but is selected at run-time depending on what sub-program actually calls the method. It could be considered a place-holder in the definition of the class.<br />
*'''override''' means that at run-time the locally given definition can take the place of a definition inherited from an ancestor class, particularly if it was '''virtual'''. If you particularly want to use the method defined in the ancestor class, it is sometimes necessary to call it specifically with the '''inherited''' clause.<br />
<br />
Methods with no virtual or override directive are '''static''' methods (the usual kind in Pascal). Those with a virtual or override directive are '''dynamic'''.<br />
<br />
Special instances of methods are:<br />
*'''create''' - a '''constructor''' for a class, which takes care of allocating memory, collecting together all the information needed and configuring/initializing the various properties.<br />
*'''destroy''' - a '''destructor''' for a class, which removes all the parts of the class from the system in an orderly and logical way, and returns all its resources for the system to re-use.<br />
<br />
=== Properties ===<br />
<br />
Properties are just like ordinary fields in a conventional Pascal record, but they can have '''read''' and/or '''write''' specifiers.<br />
*'''read''' specifier is a field, or a function that returns a result of the correct type for the property. In the example above, the property ''Color'' has a read specifier ''FColor'', which is a local variable containing the value to be used. If a property has a '''read''' but no '''write''' specifier, it is read-only.<br />
*'''write''' specifier is a field, or a procedure that will store the value of the property in a specific location. In the example above, ''Color'' has a write specifier ''SetColor'' that is a procedure (defined in the '''protected''' section) for writing the color value to some specified location. If a property has a '''write''' but no '''read''' specifier, it is write-only.<br />
*'''default''' - note that it is possible to set a '''default''' value for a property. For example, ''Color'' here is given the default value ''clBlack'', or black, at the time of creation. It could subsequently be given a different value, by a programming assignment statement, or in the Object Inspector.<br />
<br />
<br />
== Further information ==<br />
<br />
This has only scratched the surface of the topic. For more details, readers are strongly recommended to read the [http://lazarus-ccr.sourceforge.net/fpcdoc/ref/ref.html FreePascal] manuals, especially Chapters 5 ('''Objects''') and 6 ('''Classes''')<br />
<br />
--[[User:Kirkpatc|Kirkpatc]] 11:04, 20 July 2008 (CEST)<br />
<br />
----<br />
[[Console Mode Pascal]]</div>Amedeohttps://wiki.freepascal.org/index.php?title=Object_Oriented_Programming_with_Free_Pascal_and_Lazarus/it&diff=34721Object Oriented Programming with Free Pascal and Lazarus/it2009-03-30T12:13:02Z<p>Amedeo: </p>
<hr />
<div>{{Programmazione_Orientata_agli_Oggetti_con_FreePascal_e_Lazarus}}<br />
<br />
Esistono molte guide eccellenti su Pascal, ma questa guida tenta di prendere il principiante ulteriormente, in [[Glossary#OO | Object-Oriented Programming]], che è un'estensione dello standard pascal, offerta da Turbo pascal, Delphi e FreePascal/Lazarus.<br />
<br />
Un [[Glossary#Object | Object]] è un'estensione della struttura standard pascal [http://wiki.lazarus.freepascal.org/Record record]<br />
<br />
La programmazione Pascal in testo standard è adatta alla creazione di applicazioni che, come le applicazioni Unix tradizionali,sono adatte per fare una cosa e per farla molto bene.<br />
<br />
Ciò che un programma fa può essere un'azione veramente complicata ,e può offrire all'utente molte opzioni di menu,<br />
ma è essenzialmente ristretta ad obbedire a comandi che l'utente digita da tastiera e a listare le sue risposte sul terminale o sulla stampante. <br />
<br />
In order to provide a [[Glossary#GUI | Graphical User Interface (GUI)]] it is usual to invoke some sort of Object-Oriented Programming method (often making use of [[Glossary#C Programming Language | C]] or one of its variants, or Visual Basic, or one of the [[Glossary#OO | OO]] variants of Pascal such as [[Glossary#FreePascal | FreePascal]] with or without [[Glossary#Lazarus | Lazarus]]). <br />
<br />
In a GUI the user is presented with a screen with a large number of images arranged in a structured way, consisting of a set of tools or [[Glossary#Widget | Widgets]] that are associated with various actions such as <br />
*selecting from a menu, <br />
*opening or saving files, <br />
*connecting to the Internet, <br />
*performing numerical computations, etc. <br />
<br />
The user is expected to move a mouse or other pointer/selection tool over the screen, to select actions which are to be performed in response to a mouse button click or a key-press.<br />
<br />
While systems to deal with a complex graphical user interface could be written in standard Pascal or almost any other programming language, it is much easier to use an object-oriented system, in which each graphical object on the screen can have all its properties and the procedures and functions associated with its use kept together in a common structure.<br />
<br />
<br />
== Objects - a real-world analogy == <br />
Consider the analogy of a blood sample collected in a hospital or a doctor's office.<br />
=== Blood Sample ===<br />
The physical sample is certainly an '''object'''; it has, associated with it, a lot of information, documents and other physical objects. <br />
<br />
*'''Sample tube''', of a type determined by the test that the physician wants performed.<br />
<br />
*'''Local rule''' (or ''method'', ''standard operating procedure'') to direct the nurse or technician collecting the sample <br />
**which type of tube to use, <br />
**how to process the sample <br />
**how to store it before transfer to the lab. <br />
<br />
*'''Label''' on the tube with details of the <br />
**sample identifier<br />
**patient's name and birthdate<br />
**date and time of collection <br />
**tests required. <br />
<br />
*'''Request form''' that accompanies the sample to the lab, directing <br />
**sample ID<br />
**ID of requesting physician<br />
**what test the physician requests and <br />
**giving fuller details of the patient<br />
**the possible diagnosis for which confirmation is sought. <br />
<br />
A copy of the request form is placed in the patient's notes, to remind the physician to expect results within an appropriate time. <br />
<br />
*In the lab - '''local methods''' to determine <br />
**how the sample is to be analysed, <br />
**what machines to use, <br />
**how the machines are to be calibrated and operated, <br />
**how the results are to be stored, formatted and <br />
**reported back to the physician. <br />
<br />
The actual '''results''' are a record that the physician uses to assist the diagnosis, and a copy of the results is filed in the patient notes.<br />
<br />
The physical sample might be retained for reference, confirmation or further tests, or might be disposed of by pouring down the sink or by incineration; there will be a method to describe this.<br />
<br />
There is no need for a physician to spell out all the details and instructions every time a sample is collected; indeed, he may have very little knowledge of how the sample is processed in the lab. The details of the various processes are '''inherited''' from previous sample collections and analyses - there will be a generic plan for the whole sequence, and together we could think of the blood sample, all its documents and data, and the underlying methods, as a complex '''object'''. <br />
<br />
In the physician's mind, the blood sample is seen as almost the same entity as its results, and to the nurses and technicians the sample, the tube, the label and the storage conditions again form a single entity.<br />
=== Another Example - Automobile ===<br />
If you don't like blood, the same sort of reasoning could be applied to a car taken to a garage for repair.<br />
It might consist of:<br />
*the physical vehicle<br />
*documents held by the owner: registration or license (including license plates), insurance, receipts for purchase, parts, repairs etc<br />
*the fuel consumption history<br />
*the drivers allowed to use the vehicle, with their license particulars<br />
*service records held by the garage<br />
*methods or procedures to be followed for routine checking and maintenance<br />
*methods to be followed for non-routine repairs etc<br />
*billing information for the customer<br />
<br />
== Programming Example ==<br />
<br />
Enough of this pre-occupation with Real-World examples! Let us proceed to the main purpose: programming in FreePascal.<br />
<br />
Let us consider the creation of a simple Form with a few controls for an application in FreePascal/Lazarus.<br />
<br />
<div class="floatleft">[[Image:ObjectInspector-TForm.png]]</div><br />
<div class="floatright">[[Image:BlankForm.png]]</div><br />
<br />
On invoking the Lazarus IDE, the programmer is presented with a blank template Form design, on which he is encouraged to place various controls or objects.<br />
<br />
Note that the pre-made blank Form is already an Object, with its own properties such as position (Top and Left), size (Height and Width), colour, default font for adding text etc.<br />
<br />
<br />
<br />
----<br />
<br />
If a Button control is placed on the Form (type TButton), it will have its own series of properties, which can be examined in the Object Inspector window. <br />
<br />
Several of the properties have names similar to those for the Form; this is because many properties are '''Inherited''' from some common Ancestor class, which lays out how properties are to be defined and handled by the descendant classes. <br />
<br />
As well as properties, the Object Inspector offers a tab called '''Events''', which gives access to Event Handlers which are methods instructing the application how to deal with things such as a mouse click on a button (OnClick) or some change in the position, size or other properties (OnChange).<br />
<br />
The physical image of the Button on the Form, together with all its properties and Event Handler methods, should be regarded as a single entity or '''Object''' in Pascal.<br />
<br />
<div class="floatleft">[[Image:ObjectInspector-TButton.png]]</div><br />
<div class="floatright">[[Image:FormWithButton.png]]</div><br />
<div class="floatright">[[Image:Source_FormWithButton1.png ]]</div><br />
<br />
== Object-Oriented Extensions to standard Pascal ==<br />
<br />
The Pascal record structure is extended by defining an <br />
=== Object ===<br />
<br />
An Object is a special kind of record. The record contains all the fields that<br />
are declared in the object's definition (just like a conventional record), but now procedures and functions can be declared as if they were part of the record and are held as pointers to the methods associated with the object's type. <br />
<br />
For example, an object could contain an array of real values, together with a Method for calculating the average.<br />
<br />
Type<br />
Average = Object<br />
NumVal: Integer;<br />
Values: Array [1..200] of Real;<br />
Function Mean: Real; { calculates the average value of the array }<br />
End;<br />
<br />
Objects can ”inherit” fields and methods from ”parent” objects. This means that these fields and methods can be used as if they were included in the objects declared as a ”child” object.<br />
<br />
Furthermore, a concept of visibility is introduced: fields, procedures and functions can be declared<br />
as public, protected or private. By default, fields and methods are public, and can be exported outside the<br />
current unit. Protected fields or methods are available only to objects descended from the current ancestor object. Fields or methods that are declared private are only accessible in the current unit:<br />
their scope is limited to the implementation of the current unit.<br />
<br />
=== Class ===<br />
Objects are not used very often by themselves in FreePascal and Lazarus; instead, Classes are used very widely. A Class is defined in almost the same way as an Object, but is a pointer to an Object rather than the Object itself. Technically, this means that the Class is allocated on the Heap of a program, whereas the Object is allocated on the Stack.<br />
<br />
Here is a simple example of a typical Class declaration:<br />
{-----------------------------------------}<br />
{example of Class declaration from the LCL}<br />
{-----------------------------------------}<br />
TPen = class(TFPCustomPen)<br />
private<br />
FColor: TColor;<br />
FPenHandleCached: boolean;<br />
FReference: TWSPenReference;<br />
procedure FreeReference;<br />
function GetHandle: HPEN;<br />
function GetReference: TWSPenReference;<br />
procedure ReferenceNeeded;<br />
procedure SetHandle(const Value: HPEN);<br />
protected<br />
procedure DoAllocateResources; override;<br />
procedure DoDeAllocateResources; override;<br />
procedure DoCopyProps(From: TFPCanvasHelper); override;<br />
procedure SetColor<br />
(const NewColor: TColor; const NewFPColor: TFPColor); virtual;<br />
procedure SetFPColor(const AValue: TFPColor); override;<br />
procedure SetColor(Value: TColor);<br />
procedure SetMode(Value: TPenMode); override;<br />
procedure SetStyle(Value: TPenStyle); override;<br />
procedure SetWidth(value: Integer); override;<br />
public<br />
constructor Create; override;<br />
destructor Destroy; override;<br />
procedure Assign(Source: TPersistent); override;<br />
property Handle: HPEN read GetHandle write SetHandle; deprecated;<br />
property Reference: TWSPenReference read GetReference;<br />
published<br />
property Color: TColor read FColor write SetColor default clBlack;<br />
property Mode default pmCopy;<br />
property Style default psSolid;<br />
property Width default 1;<br />
end;<br />
<br />
<br />
Note that this class is defined as an instance of another '''parent''' or '''ancestor''' class (''TFPCustomPen'') from which it '''inherits''' all its properties and methods. It has some fields of its own, grouped under<br />
*'''private''' - this means that items defined here are only available or visible to other classes or procedures/function defined within the same program unit (this example is from ''Graphics'', so any of the other classes such as ''TBitMap'', ''TPicture'' etc in the same unit can use them). They are essentially local variables (eg ''FColor'', ''FPenHandleCached'') or locally used methods (''GetHandle'', ''SetHandle'') but can be used or referred to in items declared in the '''protected''' or '''public''' sections.<br />
*'''protected''' - this means that items defined here are only available or visible to classes that are descended from this '''ancestor''' class, and inherit its properties or methods<br />
*'''public''' - this means that items defined here are available to any programming unit that includes the current unit in its [[Glossary#Uses | Uses]] clause <br />
*'''published''' - is the same as a '''public''' section, but the compiler also generates type information that is needed for automatic streaming of these classes. Often the list of published items appear in the Object Inspector of Lazarus; if there is no '''published''' list, all the '''public''' fields usually appear in the Object Inspector.<br />
<br />
=== Methods ===<br />
A method is just like a standard procedure or function, but can have some additional '''directives'''.<br />
<br />
Some of the methods defined above are labelled with the directive '''virtual'''; others are labelled with the '''override''' directive.<br />
*'''virtual''' means that the type or actual instance of a method is not known at compile-time, but is selected at run-time depending on what sub-program actually calls the method. It could be considered a place-holder in the definition of the class.<br />
*'''override''' means that at run-time the locally given definition can take the place of a definition inherited from an ancestor class, particularly if it was '''virtual'''. If you particularly want to use the method defined in the ancestor class, it is sometimes necessary to call it specifically with the '''inherited''' clause.<br />
<br />
Methods with no virtual or override directive are '''static''' methods (the usual kind in Pascal). Those with a virtual or override directive are '''dynamic'''.<br />
<br />
Special instances of methods are:<br />
*'''create''' - a '''constructor''' for a class, which takes care of allocating memory, collecting together all the information needed and configuring/initializing the various properties.<br />
*'''destroy''' - a '''destructor''' for a class, which removes all the parts of the class from the system in an orderly and logical way, and returns all its resources for the system to re-use.<br />
<br />
=== Properties ===<br />
<br />
Properties are just like ordinary fields in a conventional Pascal record, but they can have '''read''' and/or '''write''' specifiers.<br />
*'''read''' specifier is a field, or a function that returns a result of the correct type for the property. In the example above, the property ''Color'' has a read specifier ''FColor'', which is a local variable containing the value to be used. If a property has a '''read''' but no '''write''' specifier, it is read-only.<br />
*'''write''' specifier is a field, or a procedure that will store the value of the property in a specific location. In the example above, ''Color'' has a write specifier ''SetColor'' that is a procedure (defined in the '''protected''' section) for writing the color value to some specified location. If a property has a '''write''' but no '''read''' specifier, it is write-only.<br />
*'''default''' - note that it is possible to set a '''default''' value for a property. For example, ''Color'' here is given the default value ''clBlack'', or black, at the time of creation. It could subsequently be given a different value, by a programming assignment statement, or in the Object Inspector.<br />
<br />
<br />
== Further information ==<br />
<br />
This has only scratched the surface of the topic. For more details, readers are strongly recommended to read the [http://lazarus-ccr.sourceforge.net/fpcdoc/ref/ref.html FreePascal] manuals, especially Chapters 5 ('''Objects''') and 6 ('''Classes''')<br />
<br />
--[[User:Kirkpatc|Kirkpatc]] 11:04, 20 July 2008 (CEST)<br />
<br />
----<br />
[[Console Mode Pascal]]</div>Amedeohttps://wiki.freepascal.org/index.php?title=Object_Oriented_Programming_with_Free_Pascal_and_Lazarus/it&diff=34720Object Oriented Programming with Free Pascal and Lazarus/it2009-03-30T11:54:48Z<p>Amedeo: </p>
<hr />
<div>{{Programmazione_Orientata_agli_Oggetti_con_FreePascal_e_Lazarus}}<br />
<br />
Esistono molte guide eccellenti su Pascal, ma questa guida tenta di prendere il principiante ulteriormente, in [[Glossary#OO | Object-Oriented Programming]], che è un'estensione dello standard pascal, offerta da Turbo pascal, Delphi e FreePascal/Lazarus.<br />
<br />
Un [[Glossary#Object | Object]] è un'estensione della struttura standard pascal [http://wiki.lazarus.freepascal.org/Record record]<br />
<br />
Standard text-based Pascal programming is good for creating applications which, like traditional Unix applications, do one thing and do it very well. The 'one thing' that a program does might be a very complicated action, and might offer the user several menu-driven options, but it is essentially restricted to obeying commands that the user types at the keyboard and listing its responses on the terminal or a printer. <br />
<br />
In order to provide a [[Glossary#GUI | Graphical User Interface (GUI)]] it is usual to invoke some sort of Object-Oriented Programming method (often making use of [[Glossary#C Programming Language | C]] or one of its variants, or Visual Basic, or one of the [[Glossary#OO | OO]] variants of Pascal such as [[Glossary#FreePascal | FreePascal]] with or without [[Glossary#Lazarus | Lazarus]]). <br />
<br />
In a GUI the user is presented with a screen with a large number of images arranged in a structured way, consisting of a set of tools or [[Glossary#Widget | Widgets]] that are associated with various actions such as <br />
*selecting from a menu, <br />
*opening or saving files, <br />
*connecting to the Internet, <br />
*performing numerical computations, etc. <br />
<br />
The user is expected to move a mouse or other pointer/selection tool over the screen, to select actions which are to be performed in response to a mouse button click or a key-press.<br />
<br />
While systems to deal with a complex graphical user interface could be written in standard Pascal or almost any other programming language, it is much easier to use an object-oriented system, in which each graphical object on the screen can have all its properties and the procedures and functions associated with its use kept together in a common structure.<br />
<br />
<br />
== Objects - a real-world analogy == <br />
Consider the analogy of a blood sample collected in a hospital or a doctor's office.<br />
=== Blood Sample ===<br />
The physical sample is certainly an '''object'''; it has, associated with it, a lot of information, documents and other physical objects. <br />
<br />
*'''Sample tube''', of a type determined by the test that the physician wants performed.<br />
<br />
*'''Local rule''' (or ''method'', ''standard operating procedure'') to direct the nurse or technician collecting the sample <br />
**which type of tube to use, <br />
**how to process the sample <br />
**how to store it before transfer to the lab. <br />
<br />
*'''Label''' on the tube with details of the <br />
**sample identifier<br />
**patient's name and birthdate<br />
**date and time of collection <br />
**tests required. <br />
<br />
*'''Request form''' that accompanies the sample to the lab, directing <br />
**sample ID<br />
**ID of requesting physician<br />
**what test the physician requests and <br />
**giving fuller details of the patient<br />
**the possible diagnosis for which confirmation is sought. <br />
<br />
A copy of the request form is placed in the patient's notes, to remind the physician to expect results within an appropriate time. <br />
<br />
*In the lab - '''local methods''' to determine <br />
**how the sample is to be analysed, <br />
**what machines to use, <br />
**how the machines are to be calibrated and operated, <br />
**how the results are to be stored, formatted and <br />
**reported back to the physician. <br />
<br />
The actual '''results''' are a record that the physician uses to assist the diagnosis, and a copy of the results is filed in the patient notes.<br />
<br />
The physical sample might be retained for reference, confirmation or further tests, or might be disposed of by pouring down the sink or by incineration; there will be a method to describe this.<br />
<br />
There is no need for a physician to spell out all the details and instructions every time a sample is collected; indeed, he may have very little knowledge of how the sample is processed in the lab. The details of the various processes are '''inherited''' from previous sample collections and analyses - there will be a generic plan for the whole sequence, and together we could think of the blood sample, all its documents and data, and the underlying methods, as a complex '''object'''. <br />
<br />
In the physician's mind, the blood sample is seen as almost the same entity as its results, and to the nurses and technicians the sample, the tube, the label and the storage conditions again form a single entity.<br />
=== Another Example - Automobile ===<br />
If you don't like blood, the same sort of reasoning could be applied to a car taken to a garage for repair.<br />
It might consist of:<br />
*the physical vehicle<br />
*documents held by the owner: registration or license (including license plates), insurance, receipts for purchase, parts, repairs etc<br />
*the fuel consumption history<br />
*the drivers allowed to use the vehicle, with their license particulars<br />
*service records held by the garage<br />
*methods or procedures to be followed for routine checking and maintenance<br />
*methods to be followed for non-routine repairs etc<br />
*billing information for the customer<br />
<br />
== Programming Example ==<br />
<br />
Enough of this pre-occupation with Real-World examples! Let us proceed to the main purpose: programming in FreePascal.<br />
<br />
Let us consider the creation of a simple Form with a few controls for an application in FreePascal/Lazarus.<br />
<br />
<div class="floatleft">[[Image:ObjectInspector-TForm.png]]</div><br />
<div class="floatright">[[Image:BlankForm.png]]</div><br />
<br />
On invoking the Lazarus IDE, the programmer is presented with a blank template Form design, on which he is encouraged to place various controls or objects.<br />
<br />
Note that the pre-made blank Form is already an Object, with its own properties such as position (Top and Left), size (Height and Width), colour, default font for adding text etc.<br />
<br />
<br />
<br />
----<br />
<br />
If a Button control is placed on the Form (type TButton), it will have its own series of properties, which can be examined in the Object Inspector window. <br />
<br />
Several of the properties have names similar to those for the Form; this is because many properties are '''Inherited''' from some common Ancestor class, which lays out how properties are to be defined and handled by the descendant classes. <br />
<br />
As well as properties, the Object Inspector offers a tab called '''Events''', which gives access to Event Handlers which are methods instructing the application how to deal with things such as a mouse click on a button (OnClick) or some change in the position, size or other properties (OnChange).<br />
<br />
The physical image of the Button on the Form, together with all its properties and Event Handler methods, should be regarded as a single entity or '''Object''' in Pascal.<br />
<br />
<div class="floatleft">[[Image:ObjectInspector-TButton.png]]</div><br />
<div class="floatright">[[Image:FormWithButton.png]]</div><br />
<div class="floatright">[[Image:Source_FormWithButton1.png ]]</div><br />
<br />
== Object-Oriented Extensions to standard Pascal ==<br />
<br />
The Pascal record structure is extended by defining an <br />
=== Object ===<br />
<br />
An Object is a special kind of record. The record contains all the fields that<br />
are declared in the object's definition (just like a conventional record), but now procedures and functions can be declared as if they were part of the record and are held as pointers to the methods associated with the object's type. <br />
<br />
For example, an object could contain an array of real values, together with a Method for calculating the average.<br />
<br />
Type<br />
Average = Object<br />
NumVal: Integer;<br />
Values: Array [1..200] of Real;<br />
Function Mean: Real; { calculates the average value of the array }<br />
End;<br />
<br />
Objects can ”inherit” fields and methods from ”parent” objects. This means that these fields and methods can be used as if they were included in the objects declared as a ”child” object.<br />
<br />
Furthermore, a concept of visibility is introduced: fields, procedures and functions can be declared<br />
as public, protected or private. By default, fields and methods are public, and can be exported outside the<br />
current unit. Protected fields or methods are available only to objects descended from the current ancestor object. Fields or methods that are declared private are only accessible in the current unit:<br />
their scope is limited to the implementation of the current unit.<br />
<br />
=== Class ===<br />
Objects are not used very often by themselves in FreePascal and Lazarus; instead, Classes are used very widely. A Class is defined in almost the same way as an Object, but is a pointer to an Object rather than the Object itself. Technically, this means that the Class is allocated on the Heap of a program, whereas the Object is allocated on the Stack.<br />
<br />
Here is a simple example of a typical Class declaration:<br />
{-----------------------------------------}<br />
{example of Class declaration from the LCL}<br />
{-----------------------------------------}<br />
TPen = class(TFPCustomPen)<br />
private<br />
FColor: TColor;<br />
FPenHandleCached: boolean;<br />
FReference: TWSPenReference;<br />
procedure FreeReference;<br />
function GetHandle: HPEN;<br />
function GetReference: TWSPenReference;<br />
procedure ReferenceNeeded;<br />
procedure SetHandle(const Value: HPEN);<br />
protected<br />
procedure DoAllocateResources; override;<br />
procedure DoDeAllocateResources; override;<br />
procedure DoCopyProps(From: TFPCanvasHelper); override;<br />
procedure SetColor<br />
(const NewColor: TColor; const NewFPColor: TFPColor); virtual;<br />
procedure SetFPColor(const AValue: TFPColor); override;<br />
procedure SetColor(Value: TColor);<br />
procedure SetMode(Value: TPenMode); override;<br />
procedure SetStyle(Value: TPenStyle); override;<br />
procedure SetWidth(value: Integer); override;<br />
public<br />
constructor Create; override;<br />
destructor Destroy; override;<br />
procedure Assign(Source: TPersistent); override;<br />
property Handle: HPEN read GetHandle write SetHandle; deprecated;<br />
property Reference: TWSPenReference read GetReference;<br />
published<br />
property Color: TColor read FColor write SetColor default clBlack;<br />
property Mode default pmCopy;<br />
property Style default psSolid;<br />
property Width default 1;<br />
end;<br />
<br />
<br />
Note that this class is defined as an instance of another '''parent''' or '''ancestor''' class (''TFPCustomPen'') from which it '''inherits''' all its properties and methods. It has some fields of its own, grouped under<br />
*'''private''' - this means that items defined here are only available or visible to other classes or procedures/function defined within the same program unit (this example is from ''Graphics'', so any of the other classes such as ''TBitMap'', ''TPicture'' etc in the same unit can use them). They are essentially local variables (eg ''FColor'', ''FPenHandleCached'') or locally used methods (''GetHandle'', ''SetHandle'') but can be used or referred to in items declared in the '''protected''' or '''public''' sections.<br />
*'''protected''' - this means that items defined here are only available or visible to classes that are descended from this '''ancestor''' class, and inherit its properties or methods<br />
*'''public''' - this means that items defined here are available to any programming unit that includes the current unit in its [[Glossary#Uses | Uses]] clause <br />
*'''published''' - is the same as a '''public''' section, but the compiler also generates type information that is needed for automatic streaming of these classes. Often the list of published items appear in the Object Inspector of Lazarus; if there is no '''published''' list, all the '''public''' fields usually appear in the Object Inspector.<br />
<br />
=== Methods ===<br />
A method is just like a standard procedure or function, but can have some additional '''directives'''.<br />
<br />
Some of the methods defined above are labelled with the directive '''virtual'''; others are labelled with the '''override''' directive.<br />
*'''virtual''' means that the type or actual instance of a method is not known at compile-time, but is selected at run-time depending on what sub-program actually calls the method. It could be considered a place-holder in the definition of the class.<br />
*'''override''' means that at run-time the locally given definition can take the place of a definition inherited from an ancestor class, particularly if it was '''virtual'''. If you particularly want to use the method defined in the ancestor class, it is sometimes necessary to call it specifically with the '''inherited''' clause.<br />
<br />
Methods with no virtual or override directive are '''static''' methods (the usual kind in Pascal). Those with a virtual or override directive are '''dynamic'''.<br />
<br />
Special instances of methods are:<br />
*'''create''' - a '''constructor''' for a class, which takes care of allocating memory, collecting together all the information needed and configuring/initializing the various properties.<br />
*'''destroy''' - a '''destructor''' for a class, which removes all the parts of the class from the system in an orderly and logical way, and returns all its resources for the system to re-use.<br />
<br />
=== Properties ===<br />
<br />
Properties are just like ordinary fields in a conventional Pascal record, but they can have '''read''' and/or '''write''' specifiers.<br />
*'''read''' specifier is a field, or a function that returns a result of the correct type for the property. In the example above, the property ''Color'' has a read specifier ''FColor'', which is a local variable containing the value to be used. If a property has a '''read''' but no '''write''' specifier, it is read-only.<br />
*'''write''' specifier is a field, or a procedure that will store the value of the property in a specific location. In the example above, ''Color'' has a write specifier ''SetColor'' that is a procedure (defined in the '''protected''' section) for writing the color value to some specified location. If a property has a '''write''' but no '''read''' specifier, it is write-only.<br />
*'''default''' - note that it is possible to set a '''default''' value for a property. For example, ''Color'' here is given the default value ''clBlack'', or black, at the time of creation. It could subsequently be given a different value, by a programming assignment statement, or in the Object Inspector.<br />
<br />
<br />
== Further information ==<br />
<br />
This has only scratched the surface of the topic. For more details, readers are strongly recommended to read the [http://lazarus-ccr.sourceforge.net/fpcdoc/ref/ref.html FreePascal] manuals, especially Chapters 5 ('''Objects''') and 6 ('''Classes''')<br />
<br />
--[[User:Kirkpatc|Kirkpatc]] 11:04, 20 July 2008 (CEST)<br />
<br />
----<br />
[[Console Mode Pascal]]</div>Amedeohttps://wiki.freepascal.org/index.php?title=Object_Oriented_Programming_with_Free_Pascal_and_Lazarus/it&diff=34719Object Oriented Programming with Free Pascal and Lazarus/it2009-03-30T11:46:34Z<p>Amedeo: </p>
<hr />
<div>{{Programmazione_Orientata_agli_Oggetti_con_FreePascal_e_Lazarus}}<br />
<br />
There are many excellent tutorials about Pascal, but this tutorial attempts to take the beginner further, into [[Glossary#OO | Object-Oriented Programming]], which is an extension to standard Pascal, offered by Turbo-pascal, Delphi and FreePascal/Lazarus.<br />
<br />
An [[Glossary#Object | Object]] is an extension of the standard Pascal [http://wiki.lazarus.freepascal.org/Record record] structure <br />
<br />
Standard text-based Pascal programming is good for creating applications which, like traditional Unix applications, do one thing and do it very well. The 'one thing' that a program does might be a very complicated action, and might offer the user several menu-driven options, but it is essentially restricted to obeying commands that the user types at the keyboard and listing its responses on the terminal or a printer. <br />
<br />
In order to provide a [[Glossary#GUI | Graphical User Interface (GUI)]] it is usual to invoke some sort of Object-Oriented Programming method (often making use of [[Glossary#C Programming Language | C]] or one of its variants, or Visual Basic, or one of the [[Glossary#OO | OO]] variants of Pascal such as [[Glossary#FreePascal | FreePascal]] with or without [[Glossary#Lazarus | Lazarus]]). <br />
<br />
In a GUI the user is presented with a screen with a large number of images arranged in a structured way, consisting of a set of tools or [[Glossary#Widget | Widgets]] that are associated with various actions such as <br />
*selecting from a menu, <br />
*opening or saving files, <br />
*connecting to the Internet, <br />
*performing numerical computations, etc. <br />
<br />
The user is expected to move a mouse or other pointer/selection tool over the screen, to select actions which are to be performed in response to a mouse button click or a key-press.<br />
<br />
While systems to deal with a complex graphical user interface could be written in standard Pascal or almost any other programming language, it is much easier to use an object-oriented system, in which each graphical object on the screen can have all its properties and the procedures and functions associated with its use kept together in a common structure.<br />
<br />
<br />
== Objects - a real-world analogy == <br />
Consider the analogy of a blood sample collected in a hospital or a doctor's office.<br />
=== Blood Sample ===<br />
The physical sample is certainly an '''object'''; it has, associated with it, a lot of information, documents and other physical objects. <br />
<br />
*'''Sample tube''', of a type determined by the test that the physician wants performed.<br />
<br />
*'''Local rule''' (or ''method'', ''standard operating procedure'') to direct the nurse or technician collecting the sample <br />
**which type of tube to use, <br />
**how to process the sample <br />
**how to store it before transfer to the lab. <br />
<br />
*'''Label''' on the tube with details of the <br />
**sample identifier<br />
**patient's name and birthdate<br />
**date and time of collection <br />
**tests required. <br />
<br />
*'''Request form''' that accompanies the sample to the lab, directing <br />
**sample ID<br />
**ID of requesting physician<br />
**what test the physician requests and <br />
**giving fuller details of the patient<br />
**the possible diagnosis for which confirmation is sought. <br />
<br />
A copy of the request form is placed in the patient's notes, to remind the physician to expect results within an appropriate time. <br />
<br />
*In the lab - '''local methods''' to determine <br />
**how the sample is to be analysed, <br />
**what machines to use, <br />
**how the machines are to be calibrated and operated, <br />
**how the results are to be stored, formatted and <br />
**reported back to the physician. <br />
<br />
The actual '''results''' are a record that the physician uses to assist the diagnosis, and a copy of the results is filed in the patient notes.<br />
<br />
The physical sample might be retained for reference, confirmation or further tests, or might be disposed of by pouring down the sink or by incineration; there will be a method to describe this.<br />
<br />
There is no need for a physician to spell out all the details and instructions every time a sample is collected; indeed, he may have very little knowledge of how the sample is processed in the lab. The details of the various processes are '''inherited''' from previous sample collections and analyses - there will be a generic plan for the whole sequence, and together we could think of the blood sample, all its documents and data, and the underlying methods, as a complex '''object'''. <br />
<br />
In the physician's mind, the blood sample is seen as almost the same entity as its results, and to the nurses and technicians the sample, the tube, the label and the storage conditions again form a single entity.<br />
=== Another Example - Automobile ===<br />
If you don't like blood, the same sort of reasoning could be applied to a car taken to a garage for repair.<br />
It might consist of:<br />
*the physical vehicle<br />
*documents held by the owner: registration or license (including license plates), insurance, receipts for purchase, parts, repairs etc<br />
*the fuel consumption history<br />
*the drivers allowed to use the vehicle, with their license particulars<br />
*service records held by the garage<br />
*methods or procedures to be followed for routine checking and maintenance<br />
*methods to be followed for non-routine repairs etc<br />
*billing information for the customer<br />
<br />
== Programming Example ==<br />
<br />
Enough of this pre-occupation with Real-World examples! Let us proceed to the main purpose: programming in FreePascal.<br />
<br />
Let us consider the creation of a simple Form with a few controls for an application in FreePascal/Lazarus.<br />
<br />
<div class="floatleft">[[Image:ObjectInspector-TForm.png]]</div><br />
<div class="floatright">[[Image:BlankForm.png]]</div><br />
<br />
On invoking the Lazarus IDE, the programmer is presented with a blank template Form design, on which he is encouraged to place various controls or objects.<br />
<br />
Note that the pre-made blank Form is already an Object, with its own properties such as position (Top and Left), size (Height and Width), colour, default font for adding text etc.<br />
<br />
<br />
<br />
----<br />
<br />
If a Button control is placed on the Form (type TButton), it will have its own series of properties, which can be examined in the Object Inspector window. <br />
<br />
Several of the properties have names similar to those for the Form; this is because many properties are '''Inherited''' from some common Ancestor class, which lays out how properties are to be defined and handled by the descendant classes. <br />
<br />
As well as properties, the Object Inspector offers a tab called '''Events''', which gives access to Event Handlers which are methods instructing the application how to deal with things such as a mouse click on a button (OnClick) or some change in the position, size or other properties (OnChange).<br />
<br />
The physical image of the Button on the Form, together with all its properties and Event Handler methods, should be regarded as a single entity or '''Object''' in Pascal.<br />
<br />
<div class="floatleft">[[Image:ObjectInspector-TButton.png]]</div><br />
<div class="floatright">[[Image:FormWithButton.png]]</div><br />
<div class="floatright">[[Image:Source_FormWithButton1.png ]]</div><br />
<br />
== Object-Oriented Extensions to standard Pascal ==<br />
<br />
The Pascal record structure is extended by defining an <br />
=== Object ===<br />
<br />
An Object is a special kind of record. The record contains all the fields that<br />
are declared in the object's definition (just like a conventional record), but now procedures and functions can be declared as if they were part of the record and are held as pointers to the methods associated with the object's type. <br />
<br />
For example, an object could contain an array of real values, together with a Method for calculating the average.<br />
<br />
Type<br />
Average = Object<br />
NumVal: Integer;<br />
Values: Array [1..200] of Real;<br />
Function Mean: Real; { calculates the average value of the array }<br />
End;<br />
<br />
Objects can ”inherit” fields and methods from ”parent” objects. This means that these fields and methods can be used as if they were included in the objects declared as a ”child” object.<br />
<br />
Furthermore, a concept of visibility is introduced: fields, procedures and functions can be declared<br />
as public, protected or private. By default, fields and methods are public, and can be exported outside the<br />
current unit. Protected fields or methods are available only to objects descended from the current ancestor object. Fields or methods that are declared private are only accessible in the current unit:<br />
their scope is limited to the implementation of the current unit.<br />
<br />
=== Class ===<br />
Objects are not used very often by themselves in FreePascal and Lazarus; instead, Classes are used very widely. A Class is defined in almost the same way as an Object, but is a pointer to an Object rather than the Object itself. Technically, this means that the Class is allocated on the Heap of a program, whereas the Object is allocated on the Stack.<br />
<br />
Here is a simple example of a typical Class declaration:<br />
{-----------------------------------------}<br />
{example of Class declaration from the LCL}<br />
{-----------------------------------------}<br />
TPen = class(TFPCustomPen)<br />
private<br />
FColor: TColor;<br />
FPenHandleCached: boolean;<br />
FReference: TWSPenReference;<br />
procedure FreeReference;<br />
function GetHandle: HPEN;<br />
function GetReference: TWSPenReference;<br />
procedure ReferenceNeeded;<br />
procedure SetHandle(const Value: HPEN);<br />
protected<br />
procedure DoAllocateResources; override;<br />
procedure DoDeAllocateResources; override;<br />
procedure DoCopyProps(From: TFPCanvasHelper); override;<br />
procedure SetColor<br />
(const NewColor: TColor; const NewFPColor: TFPColor); virtual;<br />
procedure SetFPColor(const AValue: TFPColor); override;<br />
procedure SetColor(Value: TColor);<br />
procedure SetMode(Value: TPenMode); override;<br />
procedure SetStyle(Value: TPenStyle); override;<br />
procedure SetWidth(value: Integer); override;<br />
public<br />
constructor Create; override;<br />
destructor Destroy; override;<br />
procedure Assign(Source: TPersistent); override;<br />
property Handle: HPEN read GetHandle write SetHandle; deprecated;<br />
property Reference: TWSPenReference read GetReference;<br />
published<br />
property Color: TColor read FColor write SetColor default clBlack;<br />
property Mode default pmCopy;<br />
property Style default psSolid;<br />
property Width default 1;<br />
end;<br />
<br />
<br />
Note that this class is defined as an instance of another '''parent''' or '''ancestor''' class (''TFPCustomPen'') from which it '''inherits''' all its properties and methods. It has some fields of its own, grouped under<br />
*'''private''' - this means that items defined here are only available or visible to other classes or procedures/function defined within the same program unit (this example is from ''Graphics'', so any of the other classes such as ''TBitMap'', ''TPicture'' etc in the same unit can use them). They are essentially local variables (eg ''FColor'', ''FPenHandleCached'') or locally used methods (''GetHandle'', ''SetHandle'') but can be used or referred to in items declared in the '''protected''' or '''public''' sections.<br />
*'''protected''' - this means that items defined here are only available or visible to classes that are descended from this '''ancestor''' class, and inherit its properties or methods<br />
*'''public''' - this means that items defined here are available to any programming unit that includes the current unit in its [[Glossary#Uses | Uses]] clause <br />
*'''published''' - is the same as a '''public''' section, but the compiler also generates type information that is needed for automatic streaming of these classes. Often the list of published items appear in the Object Inspector of Lazarus; if there is no '''published''' list, all the '''public''' fields usually appear in the Object Inspector.<br />
<br />
=== Methods ===<br />
A method is just like a standard procedure or function, but can have some additional '''directives'''.<br />
<br />
Some of the methods defined above are labelled with the directive '''virtual'''; others are labelled with the '''override''' directive.<br />
*'''virtual''' means that the type or actual instance of a method is not known at compile-time, but is selected at run-time depending on what sub-program actually calls the method. It could be considered a place-holder in the definition of the class.<br />
*'''override''' means that at run-time the locally given definition can take the place of a definition inherited from an ancestor class, particularly if it was '''virtual'''. If you particularly want to use the method defined in the ancestor class, it is sometimes necessary to call it specifically with the '''inherited''' clause.<br />
<br />
Methods with no virtual or override directive are '''static''' methods (the usual kind in Pascal). Those with a virtual or override directive are '''dynamic'''.<br />
<br />
Special instances of methods are:<br />
*'''create''' - a '''constructor''' for a class, which takes care of allocating memory, collecting together all the information needed and configuring/initializing the various properties.<br />
*'''destroy''' - a '''destructor''' for a class, which removes all the parts of the class from the system in an orderly and logical way, and returns all its resources for the system to re-use.<br />
<br />
=== Properties ===<br />
<br />
Properties are just like ordinary fields in a conventional Pascal record, but they can have '''read''' and/or '''write''' specifiers.<br />
*'''read''' specifier is a field, or a function that returns a result of the correct type for the property. In the example above, the property ''Color'' has a read specifier ''FColor'', which is a local variable containing the value to be used. If a property has a '''read''' but no '''write''' specifier, it is read-only.<br />
*'''write''' specifier is a field, or a procedure that will store the value of the property in a specific location. In the example above, ''Color'' has a write specifier ''SetColor'' that is a procedure (defined in the '''protected''' section) for writing the color value to some specified location. If a property has a '''write''' but no '''read''' specifier, it is write-only.<br />
*'''default''' - note that it is possible to set a '''default''' value for a property. For example, ''Color'' here is given the default value ''clBlack'', or black, at the time of creation. It could subsequently be given a different value, by a programming assignment statement, or in the Object Inspector.<br />
<br />
<br />
== Further information ==<br />
<br />
This has only scratched the surface of the topic. For more details, readers are strongly recommended to read the [http://lazarus-ccr.sourceforge.net/fpcdoc/ref/ref.html FreePascal] manuals, especially Chapters 5 ('''Objects''') and 6 ('''Classes''')<br />
<br />
--[[User:Kirkpatc|Kirkpatc]] 11:04, 20 July 2008 (CEST)<br />
<br />
----<br />
[[Console Mode Pascal]]</div>Amedeohttps://wiki.freepascal.org/index.php?title=Object_Oriented_Programming_with_Free_Pascal_and_Lazarus/it&diff=34718Object Oriented Programming with Free Pascal and Lazarus/it2009-03-30T11:44:39Z<p>Amedeo: </p>
<hr />
<div>{{Object_Oriented_Programming_with_FreePascal_and_Lazarus}}<br />
<br />
There are many excellent tutorials about Pascal, but this tutorial attempts to take the beginner further, into [[Glossary#OO | Object-Oriented Programming]], which is an extension to standard Pascal, offered by Turbo-pascal, Delphi and FreePascal/Lazarus.<br />
<br />
An [[Glossary#Object | Object]] is an extension of the standard Pascal [http://wiki.lazarus.freepascal.org/Record record] structure <br />
<br />
Standard text-based Pascal programming is good for creating applications which, like traditional Unix applications, do one thing and do it very well. The 'one thing' that a program does might be a very complicated action, and might offer the user several menu-driven options, but it is essentially restricted to obeying commands that the user types at the keyboard and listing its responses on the terminal or a printer. <br />
<br />
In order to provide a [[Glossary#GUI | Graphical User Interface (GUI)]] it is usual to invoke some sort of Object-Oriented Programming method (often making use of [[Glossary#C Programming Language | C]] or one of its variants, or Visual Basic, or one of the [[Glossary#OO | OO]] variants of Pascal such as [[Glossary#FreePascal | FreePascal]] with or without [[Glossary#Lazarus | Lazarus]]). <br />
<br />
In a GUI the user is presented with a screen with a large number of images arranged in a structured way, consisting of a set of tools or [[Glossary#Widget | Widgets]] that are associated with various actions such as <br />
*selecting from a menu, <br />
*opening or saving files, <br />
*connecting to the Internet, <br />
*performing numerical computations, etc. <br />
<br />
The user is expected to move a mouse or other pointer/selection tool over the screen, to select actions which are to be performed in response to a mouse button click or a key-press.<br />
<br />
While systems to deal with a complex graphical user interface could be written in standard Pascal or almost any other programming language, it is much easier to use an object-oriented system, in which each graphical object on the screen can have all its properties and the procedures and functions associated with its use kept together in a common structure.<br />
<br />
<br />
== Objects - a real-world analogy == <br />
Consider the analogy of a blood sample collected in a hospital or a doctor's office.<br />
=== Blood Sample ===<br />
The physical sample is certainly an '''object'''; it has, associated with it, a lot of information, documents and other physical objects. <br />
<br />
*'''Sample tube''', of a type determined by the test that the physician wants performed.<br />
<br />
*'''Local rule''' (or ''method'', ''standard operating procedure'') to direct the nurse or technician collecting the sample <br />
**which type of tube to use, <br />
**how to process the sample <br />
**how to store it before transfer to the lab. <br />
<br />
*'''Label''' on the tube with details of the <br />
**sample identifier<br />
**patient's name and birthdate<br />
**date and time of collection <br />
**tests required. <br />
<br />
*'''Request form''' that accompanies the sample to the lab, directing <br />
**sample ID<br />
**ID of requesting physician<br />
**what test the physician requests and <br />
**giving fuller details of the patient<br />
**the possible diagnosis for which confirmation is sought. <br />
<br />
A copy of the request form is placed in the patient's notes, to remind the physician to expect results within an appropriate time. <br />
<br />
*In the lab - '''local methods''' to determine <br />
**how the sample is to be analysed, <br />
**what machines to use, <br />
**how the machines are to be calibrated and operated, <br />
**how the results are to be stored, formatted and <br />
**reported back to the physician. <br />
<br />
The actual '''results''' are a record that the physician uses to assist the diagnosis, and a copy of the results is filed in the patient notes.<br />
<br />
The physical sample might be retained for reference, confirmation or further tests, or might be disposed of by pouring down the sink or by incineration; there will be a method to describe this.<br />
<br />
There is no need for a physician to spell out all the details and instructions every time a sample is collected; indeed, he may have very little knowledge of how the sample is processed in the lab. The details of the various processes are '''inherited''' from previous sample collections and analyses - there will be a generic plan for the whole sequence, and together we could think of the blood sample, all its documents and data, and the underlying methods, as a complex '''object'''. <br />
<br />
In the physician's mind, the blood sample is seen as almost the same entity as its results, and to the nurses and technicians the sample, the tube, the label and the storage conditions again form a single entity.<br />
=== Another Example - Automobile ===<br />
If you don't like blood, the same sort of reasoning could be applied to a car taken to a garage for repair.<br />
It might consist of:<br />
*the physical vehicle<br />
*documents held by the owner: registration or license (including license plates), insurance, receipts for purchase, parts, repairs etc<br />
*the fuel consumption history<br />
*the drivers allowed to use the vehicle, with their license particulars<br />
*service records held by the garage<br />
*methods or procedures to be followed for routine checking and maintenance<br />
*methods to be followed for non-routine repairs etc<br />
*billing information for the customer<br />
<br />
== Programming Example ==<br />
<br />
Enough of this pre-occupation with Real-World examples! Let us proceed to the main purpose: programming in FreePascal.<br />
<br />
Let us consider the creation of a simple Form with a few controls for an application in FreePascal/Lazarus.<br />
<br />
<div class="floatleft">[[Image:ObjectInspector-TForm.png]]</div><br />
<div class="floatright">[[Image:BlankForm.png]]</div><br />
<br />
On invoking the Lazarus IDE, the programmer is presented with a blank template Form design, on which he is encouraged to place various controls or objects.<br />
<br />
Note that the pre-made blank Form is already an Object, with its own properties such as position (Top and Left), size (Height and Width), colour, default font for adding text etc.<br />
<br />
<br />
<br />
----<br />
<br />
If a Button control is placed on the Form (type TButton), it will have its own series of properties, which can be examined in the Object Inspector window. <br />
<br />
Several of the properties have names similar to those for the Form; this is because many properties are '''Inherited''' from some common Ancestor class, which lays out how properties are to be defined and handled by the descendant classes. <br />
<br />
As well as properties, the Object Inspector offers a tab called '''Events''', which gives access to Event Handlers which are methods instructing the application how to deal with things such as a mouse click on a button (OnClick) or some change in the position, size or other properties (OnChange).<br />
<br />
The physical image of the Button on the Form, together with all its properties and Event Handler methods, should be regarded as a single entity or '''Object''' in Pascal.<br />
<br />
<div class="floatleft">[[Image:ObjectInspector-TButton.png]]</div><br />
<div class="floatright">[[Image:FormWithButton.png]]</div><br />
<div class="floatright">[[Image:Source_FormWithButton1.png ]]</div><br />
<br />
== Object-Oriented Extensions to standard Pascal ==<br />
<br />
The Pascal record structure is extended by defining an <br />
=== Object ===<br />
<br />
An Object is a special kind of record. The record contains all the fields that<br />
are declared in the object's definition (just like a conventional record), but now procedures and functions can be declared as if they were part of the record and are held as pointers to the methods associated with the object's type. <br />
<br />
For example, an object could contain an array of real values, together with a Method for calculating the average.<br />
<br />
Type<br />
Average = Object<br />
NumVal: Integer;<br />
Values: Array [1..200] of Real;<br />
Function Mean: Real; { calculates the average value of the array }<br />
End;<br />
<br />
Objects can ”inherit” fields and methods from ”parent” objects. This means that these fields and methods can be used as if they were included in the objects declared as a ”child” object.<br />
<br />
Furthermore, a concept of visibility is introduced: fields, procedures and functions can be declared<br />
as public, protected or private. By default, fields and methods are public, and can be exported outside the<br />
current unit. Protected fields or methods are available only to objects descended from the current ancestor object. Fields or methods that are declared private are only accessible in the current unit:<br />
their scope is limited to the implementation of the current unit.<br />
<br />
=== Class ===<br />
Objects are not used very often by themselves in FreePascal and Lazarus; instead, Classes are used very widely. A Class is defined in almost the same way as an Object, but is a pointer to an Object rather than the Object itself. Technically, this means that the Class is allocated on the Heap of a program, whereas the Object is allocated on the Stack.<br />
<br />
Here is a simple example of a typical Class declaration:<br />
{-----------------------------------------}<br />
{example of Class declaration from the LCL}<br />
{-----------------------------------------}<br />
TPen = class(TFPCustomPen)<br />
private<br />
FColor: TColor;<br />
FPenHandleCached: boolean;<br />
FReference: TWSPenReference;<br />
procedure FreeReference;<br />
function GetHandle: HPEN;<br />
function GetReference: TWSPenReference;<br />
procedure ReferenceNeeded;<br />
procedure SetHandle(const Value: HPEN);<br />
protected<br />
procedure DoAllocateResources; override;<br />
procedure DoDeAllocateResources; override;<br />
procedure DoCopyProps(From: TFPCanvasHelper); override;<br />
procedure SetColor<br />
(const NewColor: TColor; const NewFPColor: TFPColor); virtual;<br />
procedure SetFPColor(const AValue: TFPColor); override;<br />
procedure SetColor(Value: TColor);<br />
procedure SetMode(Value: TPenMode); override;<br />
procedure SetStyle(Value: TPenStyle); override;<br />
procedure SetWidth(value: Integer); override;<br />
public<br />
constructor Create; override;<br />
destructor Destroy; override;<br />
procedure Assign(Source: TPersistent); override;<br />
property Handle: HPEN read GetHandle write SetHandle; deprecated;<br />
property Reference: TWSPenReference read GetReference;<br />
published<br />
property Color: TColor read FColor write SetColor default clBlack;<br />
property Mode default pmCopy;<br />
property Style default psSolid;<br />
property Width default 1;<br />
end;<br />
<br />
<br />
Note that this class is defined as an instance of another '''parent''' or '''ancestor''' class (''TFPCustomPen'') from which it '''inherits''' all its properties and methods. It has some fields of its own, grouped under<br />
*'''private''' - this means that items defined here are only available or visible to other classes or procedures/function defined within the same program unit (this example is from ''Graphics'', so any of the other classes such as ''TBitMap'', ''TPicture'' etc in the same unit can use them). They are essentially local variables (eg ''FColor'', ''FPenHandleCached'') or locally used methods (''GetHandle'', ''SetHandle'') but can be used or referred to in items declared in the '''protected''' or '''public''' sections.<br />
*'''protected''' - this means that items defined here are only available or visible to classes that are descended from this '''ancestor''' class, and inherit its properties or methods<br />
*'''public''' - this means that items defined here are available to any programming unit that includes the current unit in its [[Glossary#Uses | Uses]] clause <br />
*'''published''' - is the same as a '''public''' section, but the compiler also generates type information that is needed for automatic streaming of these classes. Often the list of published items appear in the Object Inspector of Lazarus; if there is no '''published''' list, all the '''public''' fields usually appear in the Object Inspector.<br />
<br />
=== Methods ===<br />
A method is just like a standard procedure or function, but can have some additional '''directives'''.<br />
<br />
Some of the methods defined above are labelled with the directive '''virtual'''; others are labelled with the '''override''' directive.<br />
*'''virtual''' means that the type or actual instance of a method is not known at compile-time, but is selected at run-time depending on what sub-program actually calls the method. It could be considered a place-holder in the definition of the class.<br />
*'''override''' means that at run-time the locally given definition can take the place of a definition inherited from an ancestor class, particularly if it was '''virtual'''. If you particularly want to use the method defined in the ancestor class, it is sometimes necessary to call it specifically with the '''inherited''' clause.<br />
<br />
Methods with no virtual or override directive are '''static''' methods (the usual kind in Pascal). Those with a virtual or override directive are '''dynamic'''.<br />
<br />
Special instances of methods are:<br />
*'''create''' - a '''constructor''' for a class, which takes care of allocating memory, collecting together all the information needed and configuring/initializing the various properties.<br />
*'''destroy''' - a '''destructor''' for a class, which removes all the parts of the class from the system in an orderly and logical way, and returns all its resources for the system to re-use.<br />
<br />
=== Properties ===<br />
<br />
Properties are just like ordinary fields in a conventional Pascal record, but they can have '''read''' and/or '''write''' specifiers.<br />
*'''read''' specifier is a field, or a function that returns a result of the correct type for the property. In the example above, the property ''Color'' has a read specifier ''FColor'', which is a local variable containing the value to be used. If a property has a '''read''' but no '''write''' specifier, it is read-only.<br />
*'''write''' specifier is a field, or a procedure that will store the value of the property in a specific location. In the example above, ''Color'' has a write specifier ''SetColor'' that is a procedure (defined in the '''protected''' section) for writing the color value to some specified location. If a property has a '''write''' but no '''read''' specifier, it is write-only.<br />
*'''default''' - note that it is possible to set a '''default''' value for a property. For example, ''Color'' here is given the default value ''clBlack'', or black, at the time of creation. It could subsequently be given a different value, by a programming assignment statement, or in the Object Inspector.<br />
<br />
<br />
== Further information ==<br />
<br />
This has only scratched the surface of the topic. For more details, readers are strongly recommended to read the [http://lazarus-ccr.sourceforge.net/fpcdoc/ref/ref.html FreePascal] manuals, especially Chapters 5 ('''Objects''') and 6 ('''Classes''')<br />
<br />
--[[User:Kirkpatc|Kirkpatc]] 11:04, 20 July 2008 (CEST)<br />
<br />
----<br />
[[Console Mode Pascal]]</div>Amedeohttps://wiki.freepascal.org/index.php?title=Object_Oriented_Programming_with_Free_Pascal_and_Lazarus/it&diff=34717Object Oriented Programming with Free Pascal and Lazarus/it2009-03-30T11:37:07Z<p>Amedeo: New page: Object Oriented Programming with FreePascal and Lazarus Da Lazarus-ccr. Vai a: navigazione, ricerca English (en) Español (es) Македонски (mk) Shqip (sq) There are many excelle...</p>
<hr />
<div>Object Oriented Programming with FreePascal and Lazarus<br />
Da Lazarus-ccr.<br />
Vai a: navigazione, ricerca<br />
English (en) Español (es) Македонски (mk) Shqip (sq) <br />
<br />
There are many excellent tutorials about Pascal, but this tutorial attempts to take the beginner further, into Object-Oriented Programming, which is an extension to standard Pascal, offered by Turbo-pascal, Delphi and FreePascal/Lazarus. <br />
<br />
An Object is an extension of the standard Pascal record structure <br />
<br />
Standard text-based Pascal programming is good for creating applications which, like traditional Unix applications, do one thing and do it very well. The 'one thing' that a program does might be a very complicated action, and might offer the user several menu-driven options, but it is essentially restricted to obeying commands that the user types at the keyboard and listing its responses on the terminal or a printer. <br />
<br />
In order to provide a Graphical User Interface (GUI) it is usual to invoke some sort of Object-Oriented Programming method (often making use of C or one of its variants, or Visual Basic, or one of the OO variants of Pascal such as FreePascal with or without Lazarus). <br />
<br />
In a GUI the user is presented with a screen with a large number of images arranged in a structured way, consisting of a set of tools or Widgets that are associated with various actions such as <br />
<br />
selecting from a menu, <br />
opening or saving files, <br />
connecting to the Internet, <br />
performing numerical computations, etc. <br />
The user is expected to move a mouse or other pointer/selection tool over the screen, to select actions which are to be performed in response to a mouse button click or a key-press. <br />
<br />
While systems to deal with a complex graphical user interface could be written in standard Pascal or almost any other programming language, it is much easier to use an object-oriented system, in which each graphical object on the screen can have all its properties and the procedures and functions associated with its use kept together in a common structure. <br />
<br />
<br />
<br />
<br />
Contents [hide]<br />
1 Objects - a real-world analogy <br />
1.1 Blood Sample <br />
1.2 Another Example - Automobile <br />
2 Programming Example <br />
3 Object-Oriented Extensions to standard Pascal <br />
3.1 Object <br />
3.2 Class <br />
3.3 Methods <br />
3.4 Properties <br />
4 Further information <br />
<br />
<br />
[modifica] Objects - a real-world analogy <br />
Consider the analogy of a blood sample collected in a hospital or a doctor's office. <br />
<br />
[modifica] Blood Sample <br />
The physical sample is certainly an object; it has, associated with it, a lot of information, documents and other physical objects. <br />
<br />
Sample tube, of a type determined by the test that the physician wants performed. <br />
Local rule (or method, standard operating procedure) to direct the nurse or technician collecting the sample <br />
which type of tube to use, <br />
how to process the sample <br />
how to store it before transfer to the lab. <br />
Label on the tube with details of the <br />
sample identifier <br />
patient's name and birthdate <br />
date and time of collection <br />
tests required. <br />
Request form that accompanies the sample to the lab, directing <br />
sample ID <br />
ID of requesting physician <br />
what test the physician requests and <br />
giving fuller details of the patient <br />
the possible diagnosis for which confirmation is sought. <br />
A copy of the request form is placed in the patient's notes, to remind the physician to expect results within an appropriate time. <br />
<br />
In the lab - local methods to determine <br />
how the sample is to be analysed, <br />
what machines to use, <br />
how the machines are to be calibrated and operated, <br />
how the results are to be stored, formatted and <br />
reported back to the physician. <br />
The actual results are a record that the physician uses to assist the diagnosis, and a copy of the results is filed in the patient notes. <br />
<br />
The physical sample might be retained for reference, confirmation or further tests, or might be disposed of by pouring down the sink or by incineration; there will be a method to describe this. <br />
<br />
There is no need for a physician to spell out all the details and instructions every time a sample is collected; indeed, he may have very little knowledge of how the sample is processed in the lab. The details of the various processes are inherited from previous sample collections and analyses - there will be a generic plan for the whole sequence, and together we could think of the blood sample, all its documents and data, and the underlying methods, as a complex object. <br />
<br />
In the physician's mind, the blood sample is seen as almost the same entity as its results, and to the nurses and technicians the sample, the tube, the label and the storage conditions again form a single entity. <br />
<br />
[modifica] Another Example - Automobile <br />
If you don't like blood, the same sort of reasoning could be applied to a car taken to a garage for repair. It might consist of: <br />
<br />
the physical vehicle <br />
documents held by the owner: registration or license (including license plates), insurance, receipts for purchase, parts, repairs etc <br />
the fuel consumption history <br />
the drivers allowed to use the vehicle, with their license particulars <br />
service records held by the garage <br />
methods or procedures to be followed for routine checking and maintenance <br />
methods to be followed for non-routine repairs etc <br />
billing information for the customer <br />
[modifica] Programming Example <br />
Enough of this pre-occupation with Real-World examples! Let us proceed to the main purpose: programming in FreePascal. <br />
<br />
Let us consider the creation of a simple Form with a few controls for an application in FreePascal/Lazarus. <br />
<br />
On invoking the Lazarus IDE, the programmer is presented with a blank template Form design, on which he is encouraged to place various controls or objects. <br />
<br />
Note that the pre-made blank Form is already an Object, with its own properties such as position (Top and Left), size (Height and Width), colour, default font for adding text etc. <br />
<br />
<br />
<br />
<br />
<br />
--------------------------------------------------------------------------------<br />
<br />
If a Button control is placed on the Form (type TButton), it will have its own series of properties, which can be examined in the Object Inspector window. <br />
<br />
Several of the properties have names similar to those for the Form; this is because many properties are Inherited from some common Ancestor class, which lays out how properties are to be defined and handled by the descendant classes. <br />
<br />
As well as properties, the Object Inspector offers a tab called Events, which gives access to Event Handlers which are methods instructing the application how to deal with things such as a mouse click on a button (OnClick) or some change in the position, size or other properties (OnChange). <br />
<br />
The physical image of the Button on the Form, together with all its properties and Event Handler methods, should be regarded as a single entity or Object in Pascal. <br />
<br />
[modifica] Object-Oriented Extensions to standard Pascal <br />
The Pascal record structure is extended by defining an <br />
<br />
[modifica] Object <br />
An Object is a special kind of record. The record contains all the fields that are declared in the object's definition (just like a conventional record), but now procedures and functions can be declared as if they were part of the record and are held as pointers to the methods associated with the object's type. <br />
<br />
For example, an object could contain an array of real values, together with a Method for calculating the average. <br />
<br />
Type<br />
Average = Object<br />
NumVal: Integer;<br />
Values: Array [1..200] of Real;<br />
Function Mean: Real; { calculates the average value of the array }<br />
End;<br />
Objects can ”inherit” fields and methods from ”parent” objects. This means that these fields and methods can be used as if they were included in the objects declared as a ”child” object. <br />
<br />
Furthermore, a concept of visibility is introduced: fields, procedures and functions can be declared as public, protected or private. By default, fields and methods are public, and can be exported outside the current unit. Protected fields or methods are available only to objects descended from the current ancestor object. Fields or methods that are declared private are only accessible in the current unit: their scope is limited to the implementation of the current unit. <br />
<br />
[modifica] Class <br />
Objects are not used very often by themselves in FreePascal and Lazarus; instead, Classes are used very widely. A Class is defined in almost the same way as an Object, but is a pointer to an Object rather than the Object itself. Technically, this means that the Class is allocated on the Heap of a program, whereas the Object is allocated on the Stack. <br />
<br />
Here is a simple example of a typical Class declaration: <br />
<br />
{-----------------------------------------}<br />
{example of Class declaration from the LCL}<br />
{-----------------------------------------}<br />
TPen = class(TFPCustomPen)<br />
private<br />
FColor: TColor;<br />
FPenHandleCached: boolean;<br />
FReference: TWSPenReference;<br />
procedure FreeReference;<br />
function GetHandle: HPEN;<br />
function GetReference: TWSPenReference;<br />
procedure ReferenceNeeded;<br />
procedure SetHandle(const Value: HPEN);<br />
protected<br />
procedure DoAllocateResources; override;<br />
procedure DoDeAllocateResources; override;<br />
procedure DoCopyProps(From: TFPCanvasHelper); override;<br />
procedure SetColor<br />
(const NewColor: TColor; const NewFPColor: TFPColor); virtual;<br />
procedure SetFPColor(const AValue: TFPColor); override;<br />
procedure SetColor(Value: TColor);<br />
procedure SetMode(Value: TPenMode); override;<br />
procedure SetStyle(Value: TPenStyle); override;<br />
procedure SetWidth(value: Integer); override;<br />
public<br />
constructor Create; override;<br />
destructor Destroy; override;<br />
procedure Assign(Source: TPersistent); override;<br />
property Handle: HPEN read GetHandle write SetHandle; deprecated;<br />
property Reference: TWSPenReference read GetReference;<br />
published<br />
property Color: TColor read FColor write SetColor default clBlack;<br />
property Mode default pmCopy;<br />
property Style default psSolid;<br />
property Width default 1;<br />
end;<br />
<br />
Note that this class is defined as an instance of another parent or ancestor class (TFPCustomPen) from which it inherits all its properties and methods. It has some fields of its own, grouped under <br />
<br />
private - this means that items defined here are only available or visible to other classes or procedures/function defined within the same program unit (this example is from Graphics, so any of the other classes such as TBitMap, TPicture etc in the same unit can use them). They are essentially local variables (eg FColor, FPenHandleCached) or locally used methods (GetHandle, SetHandle) but can be used or referred to in items declared in the protected or public sections. <br />
protected - this means that items defined here are only available or visible to classes that are descended from this ancestor class, and inherit its properties or methods <br />
public - this means that items defined here are available to any programming unit that includes the current unit in its Uses clause <br />
published - is the same as a public section, but the compiler also generates type information that is needed for automatic streaming of these classes. Often the list of published items appear in the Object Inspector of Lazarus; if there is no published list, all the public fields usually appear in the Object Inspector. <br />
[modifica] Methods <br />
A method is just like a standard procedure or function, but can have some additional directives. <br />
<br />
Some of the methods defined above are labelled with the directive virtual; others are labelled with the override directive. <br />
<br />
virtual means that the type or actual instance of a method is not known at compile-time, but is selected at run-time depending on what sub-program actually calls the method. It could be considered a place-holder in the definition of the class. <br />
override means that at run-time the locally given definition can take the place of a definition inherited from an ancestor class, particularly if it was virtual. If you particularly want to use the method defined in the ancestor class, it is sometimes necessary to call it specifically with the inherited clause. <br />
Methods with no virtual or override directive are static methods (the usual kind in Pascal). Those with a virtual or override directive are dynamic. <br />
<br />
Special instances of methods are: <br />
<br />
create - a constructor for a class, which takes care of allocating memory, collecting together all the information needed and configuring/initializing the various properties. <br />
destroy - a destructor for a class, which removes all the parts of the class from the system in an orderly and logical way, and returns all its resources for the system to re-use. <br />
[modifica] Properties <br />
Properties are just like ordinary fields in a conventional Pascal record, but they can have read and/or write specifiers. <br />
<br />
read specifier is a field, or a function that returns a result of the correct type for the property. In the example above, the property Color has a read specifier FColor, which is a local variable containing the value to be used. If a property has a read but no write specifier, it is read-only. <br />
write specifier is a field, or a procedure that will store the value of the property in a specific location. In the example above, Color has a write specifier SetColor that is a procedure (defined in the protected section) for writing the color value to some specified location. If a property has a write but no read specifier, it is write-only. <br />
default - note that it is possible to set a default value for a property. For example, Color here is given the default value clBlack, or black, at the time of creation. It could subsequently be given a different value, by a programming assignment statement, or in the Object Inspector. <br />
<br />
<br />
<br />
[modifica] Further information <br />
This has only scratched the surface of the topic. For more details, readers are strongly recommended to read the FreePascal manuals, especially Chapters 5 (Objects) and 6 (Classes) <br />
<br />
--Kirkpatc 11:04, 20 July 2008 (CEST) <br />
<br />
<br />
--------------------------------------------------------------------------------<br />
<br />
Console Mode Pascal <br />
<br />
Estratto da "http://wiki.lazarus.freepascal.org/Object_Oriented_Programming_with_FreePascal_and_Lazarus"</div>Amedeohttps://wiki.freepascal.org/index.php?title=Executing_External_Programs/it&diff=34105Executing External Programs/it2009-02-21T19:51:24Z<p>Amedeo: /* Un semplice esempio */</p>
<hr />
<div>{{Executing External Programs}}<br />
<br />
== Introduzione ==<br />
Ci sono molti modi di eseguire un programma esterno, ma questo articolo si focalizza solo su uno: [[doc:fcl/process/tprocess.html|TProcess]].<br />
Se usi solitamente '''ShellExecute''' e / o '''WinExec''' in Delphi, allora puoi iniziare ad usare TProcess come un'alternativa in FPC/Lazarus (Questo vale anche se usi usi Lazarus in Linux, perchè TProcess è cross-platform).<br />
<br />
'''Nota:''' FPC/Lazarus supporta '''ShellExecute''' e / o '''WinExec''', ma questo supporto è solo in Win32. Se vuoi programmare in 'cross-platform', allora usa TProcess, è la miglior scelta!<br />
<br />
<br />
== SysUtils.ExecuteProcess ==<br />
<br />
Il modo più semplice se non necessiti pipes ne ogni forma di controllo è di usare semplicemente SysUtils.ExecuteProcess('/percorso/completo/al/file/binario',['arg1','arg2']);<br />
<br />
<br />
== TProcess ==<br />
Puoi usare TProcess per lanciare programmi esterni.Alcuni benefici nell'uso di TProcess sono:<br />
<br />
*Piattaforma Indipendente<br />
*Capacità di leggere da stdout e scrivere in stdin.<br />
<br />
Nota: TProcess non è un terminal/shell! Non puoi eseguire direttamente scripts or redirigere output usando operatori tipo "|", ">", "<", "&" etc. Eì possibile ottenere gli stessi risultati con TProcess usando Pascal, qualche sempio è di seguito..<br />
<br />
Importante: Devi specificare il percorso completo all'eseguibile. Per esempio '/bin/cp' invece di 'cp'. Se il programma è nel percorso standard PATH allora puoi usare la funzione [[doc:lcl/fileutil/finddefaultexecutablepath.html|FindDefaultExecutablePath]] da [[doc:lcl/fileutil/index.html|FileUtil]] unit di LCL.<br />
<br />
=== Un semplice esempio ===<br />
<pascal><br />
// Questo è un programma dimostrativo che mostra come lanciare<br />
// un programma esterno.<br />
program launchprogram;<br />
<br />
// Qui includiamo i files che hanno utilizzo funzionale<br />
// e le procedure che ci occorreranno.<br />
uses <br />
Classes, SysUtils, Process;<br />
<br />
// Questa è la definizione della variabile var "AProcess" <br />
// come una variabile di tipo "TProcess"<br />
var <br />
AProcess: TProcess;<br />
<br />
// Qui è dove il nostro programma inizia<br />
begin<br />
// Adesso creeremo l'oggetto TProcess e<br />
// lo assegneremo alla variabile var AProcess.<br />
AProcess := TProcess.Create(nil);<br />
<br />
// Diremo al nuovo AProcess quale è il comando da eseguire.<br />
// Usa il compilatore FreePascal<br />
AProcess.CommandLine := 'ppc386 -h';<br />
<br />
// DEfiniremo una opzione per quando il programma<br />
// è in esecuzione. Questa opzione ci assicurerà che il nostro programma<br />
// non continuerà sin quando il programma che lanceremo<br />
// non sarà terminato. vvvvvvvvvvvvvv<br />
AProcess.Options := AProcess.Options + [poWaitOnExit];<br />
<br />
// Adesso che AProcess sa qual'è la linea di comando <br />
// verrò lanciato.<br />
AProcess.Execute;<br />
<br />
// Questo non avverrà sino a quandop ppc386 non fermerà la sua esecuzione.<br />
AProcess.Free; <br />
end.<br />
</pascal><br />
Questo è quanto! Hai appena imparato come eseguire un programma esterno dall'interno del tuo stesso programma.<br />
<br />
=== Un esempio comprovato ===<br />
Che bello!, ma come leggo l' Output di un programma che ho eseguito ?<br />
<br />
Bene, espandiamo il nostro esempio cosi che otteniamo questo:<br />
<br />
<delphi><br />
// This is a demo program that shows how to launch<br />
// an external program and read from it's output.<br />
program launchprogram;<br />
<br />
// Here we include files that have useful functions<br />
// and procedures we will need.<br />
uses <br />
Classes, SysUtils, Process;<br />
<br />
// This is defining the var "AProcess" as a variable <br />
// of the type "TProcess"<br />
// Also now we are adding a TStringList to store the <br />
// data read from the programs output.<br />
var <br />
AProcess: TProcess;<br />
AStringList: TStringList;<br />
<br />
// This is where our program starts to run<br />
begin<br />
// Now we will create the TProcess object, and<br />
// assign it to the var AProcess.<br />
AProcess := TProcess.Create(nil);<br />
<br />
// Create the TStringList object.<br />
AStringList := TStringList.Create;<br />
<br />
// Tell the new AProcess what the command to execute is.<br />
// Let's use the FreePascal compiler<br />
AProcess.CommandLine := 'ppc386 -h';<br />
<br />
// We will define an option for when the program<br />
// is run. This option will make sure that our program<br />
// does not continue until the program we will launch<br />
// has stopped running. Also now we will tell it that<br />
// we want to read the output of the file.<br />
AProcess.Options := AProcess.Options + [poWaitOnExit, poUsePipes];<br />
<br />
// Now that AProcess knows what the commandline is <br />
// we will run it.<br />
AProcess.Execute;<br />
<br />
// This is not reached until ppc386 stops running.<br />
<br />
// Now read the output of the program we just ran<br />
// into the TStringList.<br />
AStringList.LoadFromStream(AProcess.Output);<br />
<br />
// Save the output to a file.<br />
AStringList.SaveToFile('output.txt');<br />
<br />
// Now that the file is saved we can free the <br />
// TStringList and the TProcess.<br />
AStringList.Free;<br />
AProcess.Free; <br />
end.<br />
</delphi><br />
<br />
=== Leggere un grande output ===<br />
Nel precedente esempio noi abbiamo aspettato sinché il programma non è terminato. Ora leggiamo, quello che il programma ha scritto nel suo output. Ma supponiamo che il programma scriva molti dati nell'output, il buffer si riempie e il programma richiamato aspetta sinché il buffer non viene letto. MA il programma chiamante non legge dal buffer, sinché il programma chiamato non ha terminato. Avviene un blocco.<br />
<br />
Il seguente esempio tuttavia non usa poWaitOnExit, ma legge dall'output, mentre il programma è ancora in esecuzione. L'output è immagazzinato in un buffer di memoria, che potrà essere usato più tardi per leggere l'output in TStringList.<br />
<br />
<delphi> program procoutlarge;<br />
{<br />
Copyright (c) 2004 by Marc Weustink<br />
<br />
This example is creeated in the hope that it will be useful,<br />
but WITHOUT ANY WARRANTY; without even the implied warranty of<br />
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.<br />
}<br />
<br />
uses<br />
Classes, Process, SysUtils;<br />
<br />
const<br />
READ_BYTES = 2048;<br />
<br />
var<br />
S: TStringList;<br />
M: TMemoryStream;<br />
P: TProcess;<br />
n: LongInt;<br />
BytesRead: LongInt;<br />
<br />
begin<br />
// We cannot use poWaitOnExit here since we don't<br />
// know the size of the output. On Linux the size of the<br />
// output pipe is 2 kB. If the output data is more, we <br />
// need to read the data. This isn't possible since we are <br />
// waiting. So we get a deadlock here.<br />
//<br />
// A temp Memorystream is used to buffer the output<br />
<br />
M := TMemoryStream.Create;<br />
BytesRead := 0;<br />
<br />
P := TProcess.Create(nil);<br />
P.CommandLine := 'ppc386 -va bogus.pp';<br />
P.Options := [poUsePipes];<br />
WriteLn('-- executing --');<br />
P.Execute;<br />
while P.Running do<br />
begin <br />
// make sure we have room<br />
M.SetSize(BytesRead + READ_BYTES);<br />
<br />
// try reading it<br />
n := P.Output.Read((M.Memory + BytesRead)^, READ_BYTES);<br />
if n > 0 <br />
then begin<br />
Inc(BytesRead, n);<br />
Write('.')<br />
end<br />
else begin <br />
// no data, wait 100 ms<br />
Sleep(100); <br />
end;<br />
end;<br />
// read last part<br />
repeat<br />
// make sure we have room<br />
M.SetSize(BytesRead + READ_BYTES);<br />
// try reading it<br />
n := P.Output.Read((M.Memory + BytesRead)^, READ_BYTES);<br />
if n > 0 <br />
then begin<br />
Inc(BytesRead, n);<br />
Write('.');<br />
end;<br />
until n <= 0;<br />
if BytesRead > 0 then WriteLn;<br />
M.SetSize(BytesRead); <br />
WriteLn('-- executed --');<br />
<br />
S := TStringList.Create;<br />
S.LoadFromStream(M);<br />
WriteLn('-- linecount = ', S.Count, ' --');<br />
for n := 0 to S.Count - 1 do<br />
begin<br />
WriteLn('| ', S[n]);<br />
end;<br />
WriteLn('-- end --');<br />
S.Free;<br />
P.Free;<br />
M.Free;<br />
end.</delphi><br />
<br />
=== Usare input e output di TProcess ===<br />
Vedi l'esempio dimostrativo in [https://lazarus-ccr.svn.sourceforge.net/svnroot/lazarus-ccr/examples/process Lazarus-CCR SVN].<br />
<br />
=== Accorgimenti nell'uso di TProcess ===<br />
Se stai creando un programma multipiattaforma (cross-platform) , Puoi cambiare la linea di comando in base al Sistema Operativo , usando le direttive "{$IFDEF}s" and "{$ENDIF}s".<br />
<br />
Esempio:<br />
<delphi> {...}<br />
AProcess:TProcess.Create(nil)<br />
{$IFDEF WIN32}<br />
AProcess.CommandLine := 'calc.exe'; //Windows Calc<br />
{$ENDIF}<br />
{$IFDEF LINUX}<br />
AProcess.CommandLine := 'kcalc'; //KDE Calc<br />
{$ENDIF}<br />
AProcess.Execute; //in alternative, you can use AProcess.Active:=True<br />
{...}</delphi><br />
<br />
=== Esempio di dialogo con il processo aspell ===<br />
<br />
All'interno di [http://pasdoc.sourceforge.net/ pasdoc] Codice sorgente puoi trovare due units che fanno spell-checking mediante "dialogo" con aspell in esecuzione attraverso pipes:<br />
<br />
* [http://pasdoc.svn.sourceforge.net/viewvc/*checkout*/pasdoc/trunk/source/component/PasDoc_ProcessLineTalk.pas PasDoc_ProcessLineTalk.pas unit] implements TProcessLineTalk class, descendant of TProcess, that can be easily used to talk with any process on a line-by-line basis.<br />
<br />
* [http://pasdoc.svn.sourceforge.net/viewvc/*checkout*/pasdoc/trunk/source/component/PasDoc_Aspell.pas PasDoc_Aspell.pas units] implements TAspellProcess class, that performs spell-checking by using underlying TProcessLineTalk instance to execute aspell and communicate with running aspell process.<br />
<br />
Entrambe le units sono indipendenti dal resto di pasdoc sorgente, cosi che esse possono servire come esempio reale dell'uso di TProcess per eseguire e comunicare attraverso pipes con altri programmi.<br />
<br />
----<br />
[[TXMLPropStorage]]</div>Amedeohttps://wiki.freepascal.org/index.php?title=Executing_External_Programs/it&diff=34104Executing External Programs/it2009-02-21T16:59:49Z<p>Amedeo: /* Leggere un grande output */</p>
<hr />
<div>{{Executing External Programs}}<br />
<br />
== Introduzione ==<br />
Ci sono molti modi di eseguire un programma esterno, ma questo articolo si focalizza solo su uno: [[doc:fcl/process/tprocess.html|TProcess]].<br />
Se usi solitamente '''ShellExecute''' e / o '''WinExec''' in Delphi, allora puoi iniziare ad usare TProcess come un'alternativa in FPC/Lazarus (Questo vale anche se usi usi Lazarus in Linux, perchè TProcess è cross-platform).<br />
<br />
'''Nota:''' FPC/Lazarus supporta '''ShellExecute''' e / o '''WinExec''', ma questo supporto è solo in Win32. Se vuoi programmare in 'cross-platform', allora usa TProcess, è la miglior scelta!<br />
<br />
<br />
== SysUtils.ExecuteProcess ==<br />
<br />
Il modo più semplice se non necessiti pipes ne ogni forma di controllo è di usare semplicemente SysUtils.ExecuteProcess('/percorso/completo/al/file/binario',['arg1','arg2']);<br />
<br />
<br />
== TProcess ==<br />
Puoi usare TProcess per lanciare programmi esterni.Alcuni benefici nell'uso di TProcess sono:<br />
<br />
*Piattaforma Indipendente<br />
*Capacità di leggere da stdout e scrivere in stdin.<br />
<br />
Nota: TProcess non è un terminal/shell! Non puoi eseguire direttamente scripts or redirigere output usando operatori tipo "|", ">", "<", "&" etc. Eì possibile ottenere gli stessi risultati con TProcess usando Pascal, qualche sempio è di seguito..<br />
<br />
Importante: Devi specificare il percorso completo all'eseguibile. Per esempio '/bin/cp' invece di 'cp'. Se il programma è nel percorso standard PATH allora puoi usare la funzione [[doc:lcl/fileutil/finddefaultexecutablepath.html|FindDefaultExecutablePath]] da [[doc:lcl/fileutil/index.html|FileUtil]] unit di LCL.<br />
<br />
=== Un semplice esempio ===<br />
<pascal><br />
// Questo è un programma dimostrativo che mostra come lanciare<br />
// un mprogramma esterno.<br />
program launchprogram;<br />
<br />
// Qui includiamo i files che hanno utilizzo funzionale<br />
// e le procedure che ci occorreranno.<br />
uses <br />
Classes, SysUtils, Process;<br />
<br />
// This is defining the var "AProcess" as a variable <br />
// of the type "TProcess"<br />
var <br />
AProcess: TProcess;<br />
<br />
// This is where our program starts to run<br />
begin<br />
// Now we will create the TProcess object, and<br />
// assign it to the var AProcess.<br />
AProcess := TProcess.Create(nil);<br />
<br />
// Tell the new AProcess what the command to execute is.<br />
// Let's use the FreePascal compiler<br />
AProcess.CommandLine := 'ppc386 -h';<br />
<br />
// We will define an option for when the program<br />
// is run. This option will make sure that our program<br />
// does not continue until the program we will launch<br />
// has stopped running. vvvvvvvvvvvvvv<br />
AProcess.Options := AProcess.Options + [poWaitOnExit];<br />
<br />
// Now that AProcess knows what the commandline is <br />
// we will run it.<br />
AProcess.Execute;<br />
<br />
// This is not reached until ppc386 stops running.<br />
AProcess.Free; <br />
end.<br />
</pascal><br />
Questo è quanto! Hai appena imparato come eseguire un programma esterno dall'interno del tuo stesso programma.<br />
<br />
=== Un esempio comprovato ===<br />
Che bello!, ma come leggo l' Output di un programma che ho eseguito ?<br />
<br />
Bene, espandiamo il nostro esempio cosi che otteniamo questo:<br />
<br />
<delphi><br />
// This is a demo program that shows how to launch<br />
// an external program and read from it's output.<br />
program launchprogram;<br />
<br />
// Here we include files that have useful functions<br />
// and procedures we will need.<br />
uses <br />
Classes, SysUtils, Process;<br />
<br />
// This is defining the var "AProcess" as a variable <br />
// of the type "TProcess"<br />
// Also now we are adding a TStringList to store the <br />
// data read from the programs output.<br />
var <br />
AProcess: TProcess;<br />
AStringList: TStringList;<br />
<br />
// This is where our program starts to run<br />
begin<br />
// Now we will create the TProcess object, and<br />
// assign it to the var AProcess.<br />
AProcess := TProcess.Create(nil);<br />
<br />
// Create the TStringList object.<br />
AStringList := TStringList.Create;<br />
<br />
// Tell the new AProcess what the command to execute is.<br />
// Let's use the FreePascal compiler<br />
AProcess.CommandLine := 'ppc386 -h';<br />
<br />
// We will define an option for when the program<br />
// is run. This option will make sure that our program<br />
// does not continue until the program we will launch<br />
// has stopped running. Also now we will tell it that<br />
// we want to read the output of the file.<br />
AProcess.Options := AProcess.Options + [poWaitOnExit, poUsePipes];<br />
<br />
// Now that AProcess knows what the commandline is <br />
// we will run it.<br />
AProcess.Execute;<br />
<br />
// This is not reached until ppc386 stops running.<br />
<br />
// Now read the output of the program we just ran<br />
// into the TStringList.<br />
AStringList.LoadFromStream(AProcess.Output);<br />
<br />
// Save the output to a file.<br />
AStringList.SaveToFile('output.txt');<br />
<br />
// Now that the file is saved we can free the <br />
// TStringList and the TProcess.<br />
AStringList.Free;<br />
AProcess.Free; <br />
end.<br />
</delphi><br />
<br />
=== Leggere un grande output ===<br />
Nel precedente esempio noi abbiamo aspettato sinché il programma non è terminato. Ora leggiamo, quello che il programma ha scritto nel suo output. Ma supponiamo che il programma scriva molti dati nell'output, il buffer si riempie e il programma richiamato aspetta sinché il buffer non viene letto. MA il programma chiamante non legge dal buffer, sinché il programma chiamato non ha terminato. Avviene un blocco.<br />
<br />
Il seguente esempio tuttavia non usa poWaitOnExit, ma legge dall'output, mentre il programma è ancora in esecuzione. L'output è immagazzinato in un buffer di memoria, che potrà essere usato più tardi per leggere l'output in TStringList.<br />
<br />
<delphi> program procoutlarge;<br />
{<br />
Copyright (c) 2004 by Marc Weustink<br />
<br />
This example is creeated in the hope that it will be useful,<br />
but WITHOUT ANY WARRANTY; without even the implied warranty of<br />
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.<br />
}<br />
<br />
uses<br />
Classes, Process, SysUtils;<br />
<br />
const<br />
READ_BYTES = 2048;<br />
<br />
var<br />
S: TStringList;<br />
M: TMemoryStream;<br />
P: TProcess;<br />
n: LongInt;<br />
BytesRead: LongInt;<br />
<br />
begin<br />
// We cannot use poWaitOnExit here since we don't<br />
// know the size of the output. On Linux the size of the<br />
// output pipe is 2 kB. If the output data is more, we <br />
// need to read the data. This isn't possible since we are <br />
// waiting. So we get a deadlock here.<br />
//<br />
// A temp Memorystream is used to buffer the output<br />
<br />
M := TMemoryStream.Create;<br />
BytesRead := 0;<br />
<br />
P := TProcess.Create(nil);<br />
P.CommandLine := 'ppc386 -va bogus.pp';<br />
P.Options := [poUsePipes];<br />
WriteLn('-- executing --');<br />
P.Execute;<br />
while P.Running do<br />
begin <br />
// make sure we have room<br />
M.SetSize(BytesRead + READ_BYTES);<br />
<br />
// try reading it<br />
n := P.Output.Read((M.Memory + BytesRead)^, READ_BYTES);<br />
if n > 0 <br />
then begin<br />
Inc(BytesRead, n);<br />
Write('.')<br />
end<br />
else begin <br />
// no data, wait 100 ms<br />
Sleep(100); <br />
end;<br />
end;<br />
// read last part<br />
repeat<br />
// make sure we have room<br />
M.SetSize(BytesRead + READ_BYTES);<br />
// try reading it<br />
n := P.Output.Read((M.Memory + BytesRead)^, READ_BYTES);<br />
if n > 0 <br />
then begin<br />
Inc(BytesRead, n);<br />
Write('.');<br />
end;<br />
until n <= 0;<br />
if BytesRead > 0 then WriteLn;<br />
M.SetSize(BytesRead); <br />
WriteLn('-- executed --');<br />
<br />
S := TStringList.Create;<br />
S.LoadFromStream(M);<br />
WriteLn('-- linecount = ', S.Count, ' --');<br />
for n := 0 to S.Count - 1 do<br />
begin<br />
WriteLn('| ', S[n]);<br />
end;<br />
WriteLn('-- end --');<br />
S.Free;<br />
P.Free;<br />
M.Free;<br />
end.</delphi><br />
<br />
=== Usare input e output di TProcess ===<br />
Vedi l'esempio dimostrativo in [https://lazarus-ccr.svn.sourceforge.net/svnroot/lazarus-ccr/examples/process Lazarus-CCR SVN].<br />
<br />
=== Accorgimenti nell'uso di TProcess ===<br />
Se stai creando un programma multipiattaforma (cross-platform) , Puoi cambiare la linea di comando in base al Sistema Operativo , usando le direttive "{$IFDEF}s" and "{$ENDIF}s".<br />
<br />
Esempio:<br />
<delphi> {...}<br />
AProcess:TProcess.Create(nil)<br />
{$IFDEF WIN32}<br />
AProcess.CommandLine := 'calc.exe'; //Windows Calc<br />
{$ENDIF}<br />
{$IFDEF LINUX}<br />
AProcess.CommandLine := 'kcalc'; //KDE Calc<br />
{$ENDIF}<br />
AProcess.Execute; //in alternative, you can use AProcess.Active:=True<br />
{...}</delphi><br />
<br />
=== Esempio di dialogo con il processo aspell ===<br />
<br />
All'interno di [http://pasdoc.sourceforge.net/ pasdoc] Codice sorgente puoi trovare due units che fanno spell-checking mediante "dialogo" con aspell in esecuzione attraverso pipes:<br />
<br />
* [http://pasdoc.svn.sourceforge.net/viewvc/*checkout*/pasdoc/trunk/source/component/PasDoc_ProcessLineTalk.pas PasDoc_ProcessLineTalk.pas unit] implements TProcessLineTalk class, descendant of TProcess, that can be easily used to talk with any process on a line-by-line basis.<br />
<br />
* [http://pasdoc.svn.sourceforge.net/viewvc/*checkout*/pasdoc/trunk/source/component/PasDoc_Aspell.pas PasDoc_Aspell.pas units] implements TAspellProcess class, that performs spell-checking by using underlying TProcessLineTalk instance to execute aspell and communicate with running aspell process.<br />
<br />
Entrambe le units sono indipendenti dal resto di pasdoc sorgente, cosi che esse possono servire come esempio reale dell'uso di TProcess per eseguire e comunicare attraverso pipes con altri programmi.<br />
<br />
----<br />
[[TXMLPropStorage]]</div>Amedeohttps://wiki.freepascal.org/index.php?title=Executing_External_Programs/it&diff=34103Executing External Programs/it2009-02-21T16:56:56Z<p>Amedeo: /* Esempio di dialogo con il processo aspell */</p>
<hr />
<div>{{Executing External Programs}}<br />
<br />
== Introduzione ==<br />
Ci sono molti modi di eseguire un programma esterno, ma questo articolo si focalizza solo su uno: [[doc:fcl/process/tprocess.html|TProcess]].<br />
Se usi solitamente '''ShellExecute''' e / o '''WinExec''' in Delphi, allora puoi iniziare ad usare TProcess come un'alternativa in FPC/Lazarus (Questo vale anche se usi usi Lazarus in Linux, perchè TProcess è cross-platform).<br />
<br />
'''Nota:''' FPC/Lazarus supporta '''ShellExecute''' e / o '''WinExec''', ma questo supporto è solo in Win32. Se vuoi programmare in 'cross-platform', allora usa TProcess, è la miglior scelta!<br />
<br />
<br />
== SysUtils.ExecuteProcess ==<br />
<br />
Il modo più semplice se non necessiti pipes ne ogni forma di controllo è di usare semplicemente SysUtils.ExecuteProcess('/percorso/completo/al/file/binario',['arg1','arg2']);<br />
<br />
<br />
== TProcess ==<br />
Puoi usare TProcess per lanciare programmi esterni.Alcuni benefici nell'uso di TProcess sono:<br />
<br />
*Piattaforma Indipendente<br />
*Capacità di leggere da stdout e scrivere in stdin.<br />
<br />
Nota: TProcess non è un terminal/shell! Non puoi eseguire direttamente scripts or redirigere output usando operatori tipo "|", ">", "<", "&" etc. Eì possibile ottenere gli stessi risultati con TProcess usando Pascal, qualche sempio è di seguito..<br />
<br />
Importante: Devi specificare il percorso completo all'eseguibile. Per esempio '/bin/cp' invece di 'cp'. Se il programma è nel percorso standard PATH allora puoi usare la funzione [[doc:lcl/fileutil/finddefaultexecutablepath.html|FindDefaultExecutablePath]] da [[doc:lcl/fileutil/index.html|FileUtil]] unit di LCL.<br />
<br />
=== Un semplice esempio ===<br />
<pascal><br />
// Questo è un programma dimostrativo che mostra come lanciare<br />
// un mprogramma esterno.<br />
program launchprogram;<br />
<br />
// Qui includiamo i files che hanno utilizzo funzionale<br />
// e le procedure che ci occorreranno.<br />
uses <br />
Classes, SysUtils, Process;<br />
<br />
// This is defining the var "AProcess" as a variable <br />
// of the type "TProcess"<br />
var <br />
AProcess: TProcess;<br />
<br />
// This is where our program starts to run<br />
begin<br />
// Now we will create the TProcess object, and<br />
// assign it to the var AProcess.<br />
AProcess := TProcess.Create(nil);<br />
<br />
// Tell the new AProcess what the command to execute is.<br />
// Let's use the FreePascal compiler<br />
AProcess.CommandLine := 'ppc386 -h';<br />
<br />
// We will define an option for when the program<br />
// is run. This option will make sure that our program<br />
// does not continue until the program we will launch<br />
// has stopped running. vvvvvvvvvvvvvv<br />
AProcess.Options := AProcess.Options + [poWaitOnExit];<br />
<br />
// Now that AProcess knows what the commandline is <br />
// we will run it.<br />
AProcess.Execute;<br />
<br />
// This is not reached until ppc386 stops running.<br />
AProcess.Free; <br />
end.<br />
</pascal><br />
Questo è quanto! Hai appena imparato come eseguire un programma esterno dall'interno del tuo stesso programma.<br />
<br />
=== Un esempio comprovato ===<br />
Che bello!, ma come leggo l' Output di un programma che ho eseguito ?<br />
<br />
Bene, espandiamo il nostro esempio cosi che otteniamo questo:<br />
<br />
<delphi><br />
// This is a demo program that shows how to launch<br />
// an external program and read from it's output.<br />
program launchprogram;<br />
<br />
// Here we include files that have useful functions<br />
// and procedures we will need.<br />
uses <br />
Classes, SysUtils, Process;<br />
<br />
// This is defining the var "AProcess" as a variable <br />
// of the type "TProcess"<br />
// Also now we are adding a TStringList to store the <br />
// data read from the programs output.<br />
var <br />
AProcess: TProcess;<br />
AStringList: TStringList;<br />
<br />
// This is where our program starts to run<br />
begin<br />
// Now we will create the TProcess object, and<br />
// assign it to the var AProcess.<br />
AProcess := TProcess.Create(nil);<br />
<br />
// Create the TStringList object.<br />
AStringList := TStringList.Create;<br />
<br />
// Tell the new AProcess what the command to execute is.<br />
// Let's use the FreePascal compiler<br />
AProcess.CommandLine := 'ppc386 -h';<br />
<br />
// We will define an option for when the program<br />
// is run. This option will make sure that our program<br />
// does not continue until the program we will launch<br />
// has stopped running. Also now we will tell it that<br />
// we want to read the output of the file.<br />
AProcess.Options := AProcess.Options + [poWaitOnExit, poUsePipes];<br />
<br />
// Now that AProcess knows what the commandline is <br />
// we will run it.<br />
AProcess.Execute;<br />
<br />
// This is not reached until ppc386 stops running.<br />
<br />
// Now read the output of the program we just ran<br />
// into the TStringList.<br />
AStringList.LoadFromStream(AProcess.Output);<br />
<br />
// Save the output to a file.<br />
AStringList.SaveToFile('output.txt');<br />
<br />
// Now that the file is saved we can free the <br />
// TStringList and the TProcess.<br />
AStringList.Free;<br />
AProcess.Free; <br />
end.<br />
</delphi><br />
<br />
=== Leggere un grande output ===<br />
Nel precedente esempio noi abbiamo aspettato sinché il programma non è terminato. Ora noi leggiamo, quello che il programma ha scritto nel suo output. Ma supponiamo che il programma scriva molti dati nell'output, il buffer si riempie e il programma richiamato aspetta sinché il buffer non viene letto. MA il programma chiamante non legge dal buffer, sinché il programma chiamato non ha terminato. Avviene un blocco.<br />
<br />
Il seguente esempio tuttavia non usa poWaitOnExit, ma legge dall'output, mentre il programma è ancora in esecuzione. L'output è immagazzinato in un buffer di memoria, che potrà essere usato più tardi per leggere l'output in TStringList.<br />
<br />
<delphi> program procoutlarge;<br />
{<br />
Copyright (c) 2004 by Marc Weustink<br />
<br />
This example is creeated in the hope that it will be useful,<br />
but WITHOUT ANY WARRANTY; without even the implied warranty of<br />
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.<br />
}<br />
<br />
uses<br />
Classes, Process, SysUtils;<br />
<br />
const<br />
READ_BYTES = 2048;<br />
<br />
var<br />
S: TStringList;<br />
M: TMemoryStream;<br />
P: TProcess;<br />
n: LongInt;<br />
BytesRead: LongInt;<br />
<br />
begin<br />
// We cannot use poWaitOnExit here since we don't<br />
// know the size of the output. On Linux the size of the<br />
// output pipe is 2 kB. If the output data is more, we <br />
// need to read the data. This isn't possible since we are <br />
// waiting. So we get a deadlock here.<br />
//<br />
// A temp Memorystream is used to buffer the output<br />
<br />
M := TMemoryStream.Create;<br />
BytesRead := 0;<br />
<br />
P := TProcess.Create(nil);<br />
P.CommandLine := 'ppc386 -va bogus.pp';<br />
P.Options := [poUsePipes];<br />
WriteLn('-- executing --');<br />
P.Execute;<br />
while P.Running do<br />
begin <br />
// make sure we have room<br />
M.SetSize(BytesRead + READ_BYTES);<br />
<br />
// try reading it<br />
n := P.Output.Read((M.Memory + BytesRead)^, READ_BYTES);<br />
if n > 0 <br />
then begin<br />
Inc(BytesRead, n);<br />
Write('.')<br />
end<br />
else begin <br />
// no data, wait 100 ms<br />
Sleep(100); <br />
end;<br />
end;<br />
// read last part<br />
repeat<br />
// make sure we have room<br />
M.SetSize(BytesRead + READ_BYTES);<br />
// try reading it<br />
n := P.Output.Read((M.Memory + BytesRead)^, READ_BYTES);<br />
if n > 0 <br />
then begin<br />
Inc(BytesRead, n);<br />
Write('.');<br />
end;<br />
until n <= 0;<br />
if BytesRead > 0 then WriteLn;<br />
M.SetSize(BytesRead); <br />
WriteLn('-- executed --');<br />
<br />
S := TStringList.Create;<br />
S.LoadFromStream(M);<br />
WriteLn('-- linecount = ', S.Count, ' --');<br />
for n := 0 to S.Count - 1 do<br />
begin<br />
WriteLn('| ', S[n]);<br />
end;<br />
WriteLn('-- end --');<br />
S.Free;<br />
P.Free;<br />
M.Free;<br />
end.</delphi><br />
<br />
=== Usare input e output di TProcess ===<br />
Vedi l'esempio dimostrativo in [https://lazarus-ccr.svn.sourceforge.net/svnroot/lazarus-ccr/examples/process Lazarus-CCR SVN].<br />
<br />
=== Accorgimenti nell'uso di TProcess ===<br />
Se stai creando un programma multipiattaforma (cross-platform) , Puoi cambiare la linea di comando in base al Sistema Operativo , usando le direttive "{$IFDEF}s" and "{$ENDIF}s".<br />
<br />
Esempio:<br />
<delphi> {...}<br />
AProcess:TProcess.Create(nil)<br />
{$IFDEF WIN32}<br />
AProcess.CommandLine := 'calc.exe'; //Windows Calc<br />
{$ENDIF}<br />
{$IFDEF LINUX}<br />
AProcess.CommandLine := 'kcalc'; //KDE Calc<br />
{$ENDIF}<br />
AProcess.Execute; //in alternative, you can use AProcess.Active:=True<br />
{...}</delphi><br />
<br />
=== Esempio di dialogo con il processo aspell ===<br />
<br />
All'interno di [http://pasdoc.sourceforge.net/ pasdoc] Codice sorgente puoi trovare due units che fanno spell-checking mediante "dialogo" con aspell in esecuzione attraverso pipes:<br />
<br />
* [http://pasdoc.svn.sourceforge.net/viewvc/*checkout*/pasdoc/trunk/source/component/PasDoc_ProcessLineTalk.pas PasDoc_ProcessLineTalk.pas unit] implements TProcessLineTalk class, descendant of TProcess, that can be easily used to talk with any process on a line-by-line basis.<br />
<br />
* [http://pasdoc.svn.sourceforge.net/viewvc/*checkout*/pasdoc/trunk/source/component/PasDoc_Aspell.pas PasDoc_Aspell.pas units] implements TAspellProcess class, that performs spell-checking by using underlying TProcessLineTalk instance to execute aspell and communicate with running aspell process.<br />
<br />
Entrambe le units sono indipendenti dal resto di pasdoc sorgente, cosi che esse possono servire come esempio reale dell'uso di TProcess per eseguire e comunicare attraverso pipes con altri programmi.<br />
<br />
----<br />
[[TXMLPropStorage]]</div>Amedeohttps://wiki.freepascal.org/index.php?title=Executing_External_Programs/it&diff=34102Executing External Programs/it2009-02-21T16:48:26Z<p>Amedeo: /* Accorgimenti nell'uso di TProcess */</p>
<hr />
<div>{{Executing External Programs}}<br />
<br />
== Introduzione ==<br />
Ci sono molti modi di eseguire un programma esterno, ma questo articolo si focalizza solo su uno: [[doc:fcl/process/tprocess.html|TProcess]].<br />
Se usi solitamente '''ShellExecute''' e / o '''WinExec''' in Delphi, allora puoi iniziare ad usare TProcess come un'alternativa in FPC/Lazarus (Questo vale anche se usi usi Lazarus in Linux, perchè TProcess è cross-platform).<br />
<br />
'''Nota:''' FPC/Lazarus supporta '''ShellExecute''' e / o '''WinExec''', ma questo supporto è solo in Win32. Se vuoi programmare in 'cross-platform', allora usa TProcess, è la miglior scelta!<br />
<br />
<br />
== SysUtils.ExecuteProcess ==<br />
<br />
Il modo più semplice se non necessiti pipes ne ogni forma di controllo è di usare semplicemente SysUtils.ExecuteProcess('/percorso/completo/al/file/binario',['arg1','arg2']);<br />
<br />
<br />
== TProcess ==<br />
Puoi usare TProcess per lanciare programmi esterni.Alcuni benefici nell'uso di TProcess sono:<br />
<br />
*Piattaforma Indipendente<br />
*Capacità di leggere da stdout e scrivere in stdin.<br />
<br />
Nota: TProcess non è un terminal/shell! Non puoi eseguire direttamente scripts or redirigere output usando operatori tipo "|", ">", "<", "&" etc. Eì possibile ottenere gli stessi risultati con TProcess usando Pascal, qualche sempio è di seguito..<br />
<br />
Importante: Devi specificare il percorso completo all'eseguibile. Per esempio '/bin/cp' invece di 'cp'. Se il programma è nel percorso standard PATH allora puoi usare la funzione [[doc:lcl/fileutil/finddefaultexecutablepath.html|FindDefaultExecutablePath]] da [[doc:lcl/fileutil/index.html|FileUtil]] unit di LCL.<br />
<br />
=== Un semplice esempio ===<br />
<pascal><br />
// Questo è un programma dimostrativo che mostra come lanciare<br />
// un mprogramma esterno.<br />
program launchprogram;<br />
<br />
// Qui includiamo i files che hanno utilizzo funzionale<br />
// e le procedure che ci occorreranno.<br />
uses <br />
Classes, SysUtils, Process;<br />
<br />
// This is defining the var "AProcess" as a variable <br />
// of the type "TProcess"<br />
var <br />
AProcess: TProcess;<br />
<br />
// This is where our program starts to run<br />
begin<br />
// Now we will create the TProcess object, and<br />
// assign it to the var AProcess.<br />
AProcess := TProcess.Create(nil);<br />
<br />
// Tell the new AProcess what the command to execute is.<br />
// Let's use the FreePascal compiler<br />
AProcess.CommandLine := 'ppc386 -h';<br />
<br />
// We will define an option for when the program<br />
// is run. This option will make sure that our program<br />
// does not continue until the program we will launch<br />
// has stopped running. vvvvvvvvvvvvvv<br />
AProcess.Options := AProcess.Options + [poWaitOnExit];<br />
<br />
// Now that AProcess knows what the commandline is <br />
// we will run it.<br />
AProcess.Execute;<br />
<br />
// This is not reached until ppc386 stops running.<br />
AProcess.Free; <br />
end.<br />
</pascal><br />
Questo è quanto! Hai appena imparato come eseguire un programma esterno dall'interno del tuo stesso programma.<br />
<br />
=== Un esempio comprovato ===<br />
Che bello!, ma come leggo l' Output di un programma che ho eseguito ?<br />
<br />
Bene, espandiamo il nostro esempio cosi che otteniamo questo:<br />
<br />
<delphi><br />
// This is a demo program that shows how to launch<br />
// an external program and read from it's output.<br />
program launchprogram;<br />
<br />
// Here we include files that have useful functions<br />
// and procedures we will need.<br />
uses <br />
Classes, SysUtils, Process;<br />
<br />
// This is defining the var "AProcess" as a variable <br />
// of the type "TProcess"<br />
// Also now we are adding a TStringList to store the <br />
// data read from the programs output.<br />
var <br />
AProcess: TProcess;<br />
AStringList: TStringList;<br />
<br />
// This is where our program starts to run<br />
begin<br />
// Now we will create the TProcess object, and<br />
// assign it to the var AProcess.<br />
AProcess := TProcess.Create(nil);<br />
<br />
// Create the TStringList object.<br />
AStringList := TStringList.Create;<br />
<br />
// Tell the new AProcess what the command to execute is.<br />
// Let's use the FreePascal compiler<br />
AProcess.CommandLine := 'ppc386 -h';<br />
<br />
// We will define an option for when the program<br />
// is run. This option will make sure that our program<br />
// does not continue until the program we will launch<br />
// has stopped running. Also now we will tell it that<br />
// we want to read the output of the file.<br />
AProcess.Options := AProcess.Options + [poWaitOnExit, poUsePipes];<br />
<br />
// Now that AProcess knows what the commandline is <br />
// we will run it.<br />
AProcess.Execute;<br />
<br />
// This is not reached until ppc386 stops running.<br />
<br />
// Now read the output of the program we just ran<br />
// into the TStringList.<br />
AStringList.LoadFromStream(AProcess.Output);<br />
<br />
// Save the output to a file.<br />
AStringList.SaveToFile('output.txt');<br />
<br />
// Now that the file is saved we can free the <br />
// TStringList and the TProcess.<br />
AStringList.Free;<br />
AProcess.Free; <br />
end.<br />
</delphi><br />
<br />
=== Leggere un grande output ===<br />
Nel precedente esempio noi abbiamo aspettato sinché il programma non è terminato. Ora noi leggiamo, quello che il programma ha scritto nel suo output. Ma supponiamo che il programma scriva molti dati nell'output, il buffer si riempie e il programma richiamato aspetta sinché il buffer non viene letto. MA il programma chiamante non legge dal buffer, sinché il programma chiamato non ha terminato. Avviene un blocco.<br />
<br />
Il seguente esempio tuttavia non usa poWaitOnExit, ma legge dall'output, mentre il programma è ancora in esecuzione. L'output è immagazzinato in un buffer di memoria, che potrà essere usato più tardi per leggere l'output in TStringList.<br />
<br />
<delphi> program procoutlarge;<br />
{<br />
Copyright (c) 2004 by Marc Weustink<br />
<br />
This example is creeated in the hope that it will be useful,<br />
but WITHOUT ANY WARRANTY; without even the implied warranty of<br />
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.<br />
}<br />
<br />
uses<br />
Classes, Process, SysUtils;<br />
<br />
const<br />
READ_BYTES = 2048;<br />
<br />
var<br />
S: TStringList;<br />
M: TMemoryStream;<br />
P: TProcess;<br />
n: LongInt;<br />
BytesRead: LongInt;<br />
<br />
begin<br />
// We cannot use poWaitOnExit here since we don't<br />
// know the size of the output. On Linux the size of the<br />
// output pipe is 2 kB. If the output data is more, we <br />
// need to read the data. This isn't possible since we are <br />
// waiting. So we get a deadlock here.<br />
//<br />
// A temp Memorystream is used to buffer the output<br />
<br />
M := TMemoryStream.Create;<br />
BytesRead := 0;<br />
<br />
P := TProcess.Create(nil);<br />
P.CommandLine := 'ppc386 -va bogus.pp';<br />
P.Options := [poUsePipes];<br />
WriteLn('-- executing --');<br />
P.Execute;<br />
while P.Running do<br />
begin <br />
// make sure we have room<br />
M.SetSize(BytesRead + READ_BYTES);<br />
<br />
// try reading it<br />
n := P.Output.Read((M.Memory + BytesRead)^, READ_BYTES);<br />
if n > 0 <br />
then begin<br />
Inc(BytesRead, n);<br />
Write('.')<br />
end<br />
else begin <br />
// no data, wait 100 ms<br />
Sleep(100); <br />
end;<br />
end;<br />
// read last part<br />
repeat<br />
// make sure we have room<br />
M.SetSize(BytesRead + READ_BYTES);<br />
// try reading it<br />
n := P.Output.Read((M.Memory + BytesRead)^, READ_BYTES);<br />
if n > 0 <br />
then begin<br />
Inc(BytesRead, n);<br />
Write('.');<br />
end;<br />
until n <= 0;<br />
if BytesRead > 0 then WriteLn;<br />
M.SetSize(BytesRead); <br />
WriteLn('-- executed --');<br />
<br />
S := TStringList.Create;<br />
S.LoadFromStream(M);<br />
WriteLn('-- linecount = ', S.Count, ' --');<br />
for n := 0 to S.Count - 1 do<br />
begin<br />
WriteLn('| ', S[n]);<br />
end;<br />
WriteLn('-- end --');<br />
S.Free;<br />
P.Free;<br />
M.Free;<br />
end.</delphi><br />
<br />
=== Usare input e output di TProcess ===<br />
Vedi l'esempio dimostrativo in [https://lazarus-ccr.svn.sourceforge.net/svnroot/lazarus-ccr/examples/process Lazarus-CCR SVN].<br />
<br />
=== Accorgimenti nell'uso di TProcess ===<br />
Se stai creando un programma multipiattaforma (cross-platform) , Puoi cambiare la linea di comando in base al Sistema Operativo , usando le direttive "{$IFDEF}s" and "{$ENDIF}s".<br />
<br />
Esempio:<br />
<delphi> {...}<br />
AProcess:TProcess.Create(nil)<br />
{$IFDEF WIN32}<br />
AProcess.CommandLine := 'calc.exe'; //Windows Calc<br />
{$ENDIF}<br />
{$IFDEF LINUX}<br />
AProcess.CommandLine := 'kcalc'; //KDE Calc<br />
{$ENDIF}<br />
AProcess.Execute; //in alternative, you can use AProcess.Active:=True<br />
{...}</delphi><br />
<br />
=== Example of "talking" with aspell process ===<br />
<br />
Inside [http://pasdoc.sourceforge.net/ pasdoc] source code you can find two units that perform spell-checking by "talking" with running aspell process through pipes:<br />
<br />
* [http://pasdoc.svn.sourceforge.net/viewvc/*checkout*/pasdoc/trunk/source/component/PasDoc_ProcessLineTalk.pas PasDoc_ProcessLineTalk.pas unit] implements TProcessLineTalk class, descendant of TProcess, that can be easily used to talk with any process on a line-by-line basis.<br />
<br />
* [http://pasdoc.svn.sourceforge.net/viewvc/*checkout*/pasdoc/trunk/source/component/PasDoc_Aspell.pas PasDoc_Aspell.pas units] implements TAspellProcess class, that performs spell-checking by using underlying TProcessLineTalk instance to execute aspell and communicate with running aspell process.<br />
<br />
Both units are rather independent from the rest of pasdoc sources, so they may serve as real-world examples of using TProcess to run and communicate through pipes with other program.<br />
<br />
----<br />
[[TXMLPropStorage]]</div>Amedeohttps://wiki.freepascal.org/index.php?title=Executing_External_Programs/it&diff=34101Executing External Programs/it2009-02-21T16:45:17Z<p>Amedeo: /* Usare input e output di TProcess */</p>
<hr />
<div>{{Executing External Programs}}<br />
<br />
== Introduzione ==<br />
Ci sono molti modi di eseguire un programma esterno, ma questo articolo si focalizza solo su uno: [[doc:fcl/process/tprocess.html|TProcess]].<br />
Se usi solitamente '''ShellExecute''' e / o '''WinExec''' in Delphi, allora puoi iniziare ad usare TProcess come un'alternativa in FPC/Lazarus (Questo vale anche se usi usi Lazarus in Linux, perchè TProcess è cross-platform).<br />
<br />
'''Nota:''' FPC/Lazarus supporta '''ShellExecute''' e / o '''WinExec''', ma questo supporto è solo in Win32. Se vuoi programmare in 'cross-platform', allora usa TProcess, è la miglior scelta!<br />
<br />
<br />
== SysUtils.ExecuteProcess ==<br />
<br />
Il modo più semplice se non necessiti pipes ne ogni forma di controllo è di usare semplicemente SysUtils.ExecuteProcess('/percorso/completo/al/file/binario',['arg1','arg2']);<br />
<br />
<br />
== TProcess ==<br />
Puoi usare TProcess per lanciare programmi esterni.Alcuni benefici nell'uso di TProcess sono:<br />
<br />
*Piattaforma Indipendente<br />
*Capacità di leggere da stdout e scrivere in stdin.<br />
<br />
Nota: TProcess non è un terminal/shell! Non puoi eseguire direttamente scripts or redirigere output usando operatori tipo "|", ">", "<", "&" etc. Eì possibile ottenere gli stessi risultati con TProcess usando Pascal, qualche sempio è di seguito..<br />
<br />
Importante: Devi specificare il percorso completo all'eseguibile. Per esempio '/bin/cp' invece di 'cp'. Se il programma è nel percorso standard PATH allora puoi usare la funzione [[doc:lcl/fileutil/finddefaultexecutablepath.html|FindDefaultExecutablePath]] da [[doc:lcl/fileutil/index.html|FileUtil]] unit di LCL.<br />
<br />
=== Un semplice esempio ===<br />
<pascal><br />
// Questo è un programma dimostrativo che mostra come lanciare<br />
// un mprogramma esterno.<br />
program launchprogram;<br />
<br />
// Qui includiamo i files che hanno utilizzo funzionale<br />
// e le procedure che ci occorreranno.<br />
uses <br />
Classes, SysUtils, Process;<br />
<br />
// This is defining the var "AProcess" as a variable <br />
// of the type "TProcess"<br />
var <br />
AProcess: TProcess;<br />
<br />
// This is where our program starts to run<br />
begin<br />
// Now we will create the TProcess object, and<br />
// assign it to the var AProcess.<br />
AProcess := TProcess.Create(nil);<br />
<br />
// Tell the new AProcess what the command to execute is.<br />
// Let's use the FreePascal compiler<br />
AProcess.CommandLine := 'ppc386 -h';<br />
<br />
// We will define an option for when the program<br />
// is run. This option will make sure that our program<br />
// does not continue until the program we will launch<br />
// has stopped running. vvvvvvvvvvvvvv<br />
AProcess.Options := AProcess.Options + [poWaitOnExit];<br />
<br />
// Now that AProcess knows what the commandline is <br />
// we will run it.<br />
AProcess.Execute;<br />
<br />
// This is not reached until ppc386 stops running.<br />
AProcess.Free; <br />
end.<br />
</pascal><br />
Questo è quanto! Hai appena imparato come eseguire un programma esterno dall'interno del tuo stesso programma.<br />
<br />
=== Un esempio comprovato ===<br />
Che bello!, ma come leggo l' Output di un programma che ho eseguito ?<br />
<br />
Bene, espandiamo il nostro esempio cosi che otteniamo questo:<br />
<br />
<delphi><br />
// This is a demo program that shows how to launch<br />
// an external program and read from it's output.<br />
program launchprogram;<br />
<br />
// Here we include files that have useful functions<br />
// and procedures we will need.<br />
uses <br />
Classes, SysUtils, Process;<br />
<br />
// This is defining the var "AProcess" as a variable <br />
// of the type "TProcess"<br />
// Also now we are adding a TStringList to store the <br />
// data read from the programs output.<br />
var <br />
AProcess: TProcess;<br />
AStringList: TStringList;<br />
<br />
// This is where our program starts to run<br />
begin<br />
// Now we will create the TProcess object, and<br />
// assign it to the var AProcess.<br />
AProcess := TProcess.Create(nil);<br />
<br />
// Create the TStringList object.<br />
AStringList := TStringList.Create;<br />
<br />
// Tell the new AProcess what the command to execute is.<br />
// Let's use the FreePascal compiler<br />
AProcess.CommandLine := 'ppc386 -h';<br />
<br />
// We will define an option for when the program<br />
// is run. This option will make sure that our program<br />
// does not continue until the program we will launch<br />
// has stopped running. Also now we will tell it that<br />
// we want to read the output of the file.<br />
AProcess.Options := AProcess.Options + [poWaitOnExit, poUsePipes];<br />
<br />
// Now that AProcess knows what the commandline is <br />
// we will run it.<br />
AProcess.Execute;<br />
<br />
// This is not reached until ppc386 stops running.<br />
<br />
// Now read the output of the program we just ran<br />
// into the TStringList.<br />
AStringList.LoadFromStream(AProcess.Output);<br />
<br />
// Save the output to a file.<br />
AStringList.SaveToFile('output.txt');<br />
<br />
// Now that the file is saved we can free the <br />
// TStringList and the TProcess.<br />
AStringList.Free;<br />
AProcess.Free; <br />
end.<br />
</delphi><br />
<br />
=== Leggere un grande output ===<br />
Nel precedente esempio noi abbiamo aspettato sinché il programma non è terminato. Ora noi leggiamo, quello che il programma ha scritto nel suo output. Ma supponiamo che il programma scriva molti dati nell'output, il buffer si riempie e il programma richiamato aspetta sinché il buffer non viene letto. MA il programma chiamante non legge dal buffer, sinché il programma chiamato non ha terminato. Avviene un blocco.<br />
<br />
Il seguente esempio tuttavia non usa poWaitOnExit, ma legge dall'output, mentre il programma è ancora in esecuzione. L'output è immagazzinato in un buffer di memoria, che potrà essere usato più tardi per leggere l'output in TStringList.<br />
<br />
<delphi> program procoutlarge;<br />
{<br />
Copyright (c) 2004 by Marc Weustink<br />
<br />
This example is creeated in the hope that it will be useful,<br />
but WITHOUT ANY WARRANTY; without even the implied warranty of<br />
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.<br />
}<br />
<br />
uses<br />
Classes, Process, SysUtils;<br />
<br />
const<br />
READ_BYTES = 2048;<br />
<br />
var<br />
S: TStringList;<br />
M: TMemoryStream;<br />
P: TProcess;<br />
n: LongInt;<br />
BytesRead: LongInt;<br />
<br />
begin<br />
// We cannot use poWaitOnExit here since we don't<br />
// know the size of the output. On Linux the size of the<br />
// output pipe is 2 kB. If the output data is more, we <br />
// need to read the data. This isn't possible since we are <br />
// waiting. So we get a deadlock here.<br />
//<br />
// A temp Memorystream is used to buffer the output<br />
<br />
M := TMemoryStream.Create;<br />
BytesRead := 0;<br />
<br />
P := TProcess.Create(nil);<br />
P.CommandLine := 'ppc386 -va bogus.pp';<br />
P.Options := [poUsePipes];<br />
WriteLn('-- executing --');<br />
P.Execute;<br />
while P.Running do<br />
begin <br />
// make sure we have room<br />
M.SetSize(BytesRead + READ_BYTES);<br />
<br />
// try reading it<br />
n := P.Output.Read((M.Memory + BytesRead)^, READ_BYTES);<br />
if n > 0 <br />
then begin<br />
Inc(BytesRead, n);<br />
Write('.')<br />
end<br />
else begin <br />
// no data, wait 100 ms<br />
Sleep(100); <br />
end;<br />
end;<br />
// read last part<br />
repeat<br />
// make sure we have room<br />
M.SetSize(BytesRead + READ_BYTES);<br />
// try reading it<br />
n := P.Output.Read((M.Memory + BytesRead)^, READ_BYTES);<br />
if n > 0 <br />
then begin<br />
Inc(BytesRead, n);<br />
Write('.');<br />
end;<br />
until n <= 0;<br />
if BytesRead > 0 then WriteLn;<br />
M.SetSize(BytesRead); <br />
WriteLn('-- executed --');<br />
<br />
S := TStringList.Create;<br />
S.LoadFromStream(M);<br />
WriteLn('-- linecount = ', S.Count, ' --');<br />
for n := 0 to S.Count - 1 do<br />
begin<br />
WriteLn('| ', S[n]);<br />
end;<br />
WriteLn('-- end --');<br />
S.Free;<br />
P.Free;<br />
M.Free;<br />
end.</delphi><br />
<br />
=== Usare input e output di TProcess ===<br />
Vedi l'esempio dimostrativo in [https://lazarus-ccr.svn.sourceforge.net/svnroot/lazarus-ccr/examples/process Lazarus-CCR SVN].<br />
<br />
=== Hints on the use of TProcess ===<br />
If you are creating a cross-platform program, you can change commandline according to the OS, using directives "{$IFDEF}s" and "{$ENDIF}s".<br />
<br />
Example:<br />
<delphi> {...}<br />
AProcess:TProcess.Create(nil)<br />
{$IFDEF WIN32}<br />
AProcess.CommandLine := 'calc.exe'; //Windows Calc<br />
{$ENDIF}<br />
{$IFDEF LINUX}<br />
AProcess.CommandLine := 'kcalc'; //KDE Calc<br />
{$ENDIF}<br />
AProcess.Execute; //in alternative, you can use AProcess.Active:=True<br />
{...}</delphi><br />
<br />
=== Example of "talking" with aspell process ===<br />
<br />
Inside [http://pasdoc.sourceforge.net/ pasdoc] source code you can find two units that perform spell-checking by "talking" with running aspell process through pipes:<br />
<br />
* [http://pasdoc.svn.sourceforge.net/viewvc/*checkout*/pasdoc/trunk/source/component/PasDoc_ProcessLineTalk.pas PasDoc_ProcessLineTalk.pas unit] implements TProcessLineTalk class, descendant of TProcess, that can be easily used to talk with any process on a line-by-line basis.<br />
<br />
* [http://pasdoc.svn.sourceforge.net/viewvc/*checkout*/pasdoc/trunk/source/component/PasDoc_Aspell.pas PasDoc_Aspell.pas units] implements TAspellProcess class, that performs spell-checking by using underlying TProcessLineTalk instance to execute aspell and communicate with running aspell process.<br />
<br />
Both units are rather independent from the rest of pasdoc sources, so they may serve as real-world examples of using TProcess to run and communicate through pipes with other program.<br />
<br />
----<br />
[[TXMLPropStorage]]</div>Amedeohttps://wiki.freepascal.org/index.php?title=Executing_External_Programs/it&diff=34100Executing External Programs/it2009-02-21T16:43:31Z<p>Amedeo: /* Leggere un grande output */</p>
<hr />
<div>{{Executing External Programs}}<br />
<br />
== Introduzione ==<br />
Ci sono molti modi di eseguire un programma esterno, ma questo articolo si focalizza solo su uno: [[doc:fcl/process/tprocess.html|TProcess]].<br />
Se usi solitamente '''ShellExecute''' e / o '''WinExec''' in Delphi, allora puoi iniziare ad usare TProcess come un'alternativa in FPC/Lazarus (Questo vale anche se usi usi Lazarus in Linux, perchè TProcess è cross-platform).<br />
<br />
'''Nota:''' FPC/Lazarus supporta '''ShellExecute''' e / o '''WinExec''', ma questo supporto è solo in Win32. Se vuoi programmare in 'cross-platform', allora usa TProcess, è la miglior scelta!<br />
<br />
<br />
== SysUtils.ExecuteProcess ==<br />
<br />
Il modo più semplice se non necessiti pipes ne ogni forma di controllo è di usare semplicemente SysUtils.ExecuteProcess('/percorso/completo/al/file/binario',['arg1','arg2']);<br />
<br />
<br />
== TProcess ==<br />
Puoi usare TProcess per lanciare programmi esterni.Alcuni benefici nell'uso di TProcess sono:<br />
<br />
*Piattaforma Indipendente<br />
*Capacità di leggere da stdout e scrivere in stdin.<br />
<br />
Nota: TProcess non è un terminal/shell! Non puoi eseguire direttamente scripts or redirigere output usando operatori tipo "|", ">", "<", "&" etc. Eì possibile ottenere gli stessi risultati con TProcess usando Pascal, qualche sempio è di seguito..<br />
<br />
Importante: Devi specificare il percorso completo all'eseguibile. Per esempio '/bin/cp' invece di 'cp'. Se il programma è nel percorso standard PATH allora puoi usare la funzione [[doc:lcl/fileutil/finddefaultexecutablepath.html|FindDefaultExecutablePath]] da [[doc:lcl/fileutil/index.html|FileUtil]] unit di LCL.<br />
<br />
=== Un semplice esempio ===<br />
<pascal><br />
// Questo è un programma dimostrativo che mostra come lanciare<br />
// un mprogramma esterno.<br />
program launchprogram;<br />
<br />
// Qui includiamo i files che hanno utilizzo funzionale<br />
// e le procedure che ci occorreranno.<br />
uses <br />
Classes, SysUtils, Process;<br />
<br />
// This is defining the var "AProcess" as a variable <br />
// of the type "TProcess"<br />
var <br />
AProcess: TProcess;<br />
<br />
// This is where our program starts to run<br />
begin<br />
// Now we will create the TProcess object, and<br />
// assign it to the var AProcess.<br />
AProcess := TProcess.Create(nil);<br />
<br />
// Tell the new AProcess what the command to execute is.<br />
// Let's use the FreePascal compiler<br />
AProcess.CommandLine := 'ppc386 -h';<br />
<br />
// We will define an option for when the program<br />
// is run. This option will make sure that our program<br />
// does not continue until the program we will launch<br />
// has stopped running. vvvvvvvvvvvvvv<br />
AProcess.Options := AProcess.Options + [poWaitOnExit];<br />
<br />
// Now that AProcess knows what the commandline is <br />
// we will run it.<br />
AProcess.Execute;<br />
<br />
// This is not reached until ppc386 stops running.<br />
AProcess.Free; <br />
end.<br />
</pascal><br />
Questo è quanto! Hai appena imparato come eseguire un programma esterno dall'interno del tuo stesso programma.<br />
<br />
=== Un esempio comprovato ===<br />
Che bello!, ma come leggo l' Output di un programma che ho eseguito ?<br />
<br />
Bene, espandiamo il nostro esempio cosi che otteniamo questo:<br />
<br />
<delphi><br />
// This is a demo program that shows how to launch<br />
// an external program and read from it's output.<br />
program launchprogram;<br />
<br />
// Here we include files that have useful functions<br />
// and procedures we will need.<br />
uses <br />
Classes, SysUtils, Process;<br />
<br />
// This is defining the var "AProcess" as a variable <br />
// of the type "TProcess"<br />
// Also now we are adding a TStringList to store the <br />
// data read from the programs output.<br />
var <br />
AProcess: TProcess;<br />
AStringList: TStringList;<br />
<br />
// This is where our program starts to run<br />
begin<br />
// Now we will create the TProcess object, and<br />
// assign it to the var AProcess.<br />
AProcess := TProcess.Create(nil);<br />
<br />
// Create the TStringList object.<br />
AStringList := TStringList.Create;<br />
<br />
// Tell the new AProcess what the command to execute is.<br />
// Let's use the FreePascal compiler<br />
AProcess.CommandLine := 'ppc386 -h';<br />
<br />
// We will define an option for when the program<br />
// is run. This option will make sure that our program<br />
// does not continue until the program we will launch<br />
// has stopped running. Also now we will tell it that<br />
// we want to read the output of the file.<br />
AProcess.Options := AProcess.Options + [poWaitOnExit, poUsePipes];<br />
<br />
// Now that AProcess knows what the commandline is <br />
// we will run it.<br />
AProcess.Execute;<br />
<br />
// This is not reached until ppc386 stops running.<br />
<br />
// Now read the output of the program we just ran<br />
// into the TStringList.<br />
AStringList.LoadFromStream(AProcess.Output);<br />
<br />
// Save the output to a file.<br />
AStringList.SaveToFile('output.txt');<br />
<br />
// Now that the file is saved we can free the <br />
// TStringList and the TProcess.<br />
AStringList.Free;<br />
AProcess.Free; <br />
end.<br />
</delphi><br />
<br />
=== Leggere un grande output ===<br />
Nel precedente esempio noi abbiamo aspettato sinché il programma non è terminato. Ora noi leggiamo, quello che il programma ha scritto nel suo output. Ma supponiamo che il programma scriva molti dati nell'output, il buffer si riempie e il programma richiamato aspetta sinché il buffer non viene letto. MA il programma chiamante non legge dal buffer, sinché il programma chiamato non ha terminato. Avviene un blocco.<br />
<br />
Il seguente esempio tuttavia non usa poWaitOnExit, ma legge dall'output, mentre il programma è ancora in esecuzione. L'output è immagazzinato in un buffer di memoria, che potrà essere usato più tardi per leggere l'output in TStringList.<br />
<br />
<delphi> program procoutlarge;<br />
{<br />
Copyright (c) 2004 by Marc Weustink<br />
<br />
This example is creeated in the hope that it will be useful,<br />
but WITHOUT ANY WARRANTY; without even the implied warranty of<br />
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.<br />
}<br />
<br />
uses<br />
Classes, Process, SysUtils;<br />
<br />
const<br />
READ_BYTES = 2048;<br />
<br />
var<br />
S: TStringList;<br />
M: TMemoryStream;<br />
P: TProcess;<br />
n: LongInt;<br />
BytesRead: LongInt;<br />
<br />
begin<br />
// We cannot use poWaitOnExit here since we don't<br />
// know the size of the output. On Linux the size of the<br />
// output pipe is 2 kB. If the output data is more, we <br />
// need to read the data. This isn't possible since we are <br />
// waiting. So we get a deadlock here.<br />
//<br />
// A temp Memorystream is used to buffer the output<br />
<br />
M := TMemoryStream.Create;<br />
BytesRead := 0;<br />
<br />
P := TProcess.Create(nil);<br />
P.CommandLine := 'ppc386 -va bogus.pp';<br />
P.Options := [poUsePipes];<br />
WriteLn('-- executing --');<br />
P.Execute;<br />
while P.Running do<br />
begin <br />
// make sure we have room<br />
M.SetSize(BytesRead + READ_BYTES);<br />
<br />
// try reading it<br />
n := P.Output.Read((M.Memory + BytesRead)^, READ_BYTES);<br />
if n > 0 <br />
then begin<br />
Inc(BytesRead, n);<br />
Write('.')<br />
end<br />
else begin <br />
// no data, wait 100 ms<br />
Sleep(100); <br />
end;<br />
end;<br />
// read last part<br />
repeat<br />
// make sure we have room<br />
M.SetSize(BytesRead + READ_BYTES);<br />
// try reading it<br />
n := P.Output.Read((M.Memory + BytesRead)^, READ_BYTES);<br />
if n > 0 <br />
then begin<br />
Inc(BytesRead, n);<br />
Write('.');<br />
end;<br />
until n <= 0;<br />
if BytesRead > 0 then WriteLn;<br />
M.SetSize(BytesRead); <br />
WriteLn('-- executed --');<br />
<br />
S := TStringList.Create;<br />
S.LoadFromStream(M);<br />
WriteLn('-- linecount = ', S.Count, ' --');<br />
for n := 0 to S.Count - 1 do<br />
begin<br />
WriteLn('| ', S[n]);<br />
end;<br />
WriteLn('-- end --');<br />
S.Free;<br />
P.Free;<br />
M.Free;<br />
end.</delphi><br />
<br />
=== Using input and output of a TProcess ===<br />
See processdemo example in the [https://lazarus-ccr.svn.sourceforge.net/svnroot/lazarus-ccr/examples/process Lazarus-CCR SVN].<br />
<br />
=== Hints on the use of TProcess ===<br />
If you are creating a cross-platform program, you can change commandline according to the OS, using directives "{$IFDEF}s" and "{$ENDIF}s".<br />
<br />
Example:<br />
<delphi> {...}<br />
AProcess:TProcess.Create(nil)<br />
{$IFDEF WIN32}<br />
AProcess.CommandLine := 'calc.exe'; //Windows Calc<br />
{$ENDIF}<br />
{$IFDEF LINUX}<br />
AProcess.CommandLine := 'kcalc'; //KDE Calc<br />
{$ENDIF}<br />
AProcess.Execute; //in alternative, you can use AProcess.Active:=True<br />
{...}</delphi><br />
<br />
=== Example of "talking" with aspell process ===<br />
<br />
Inside [http://pasdoc.sourceforge.net/ pasdoc] source code you can find two units that perform spell-checking by "talking" with running aspell process through pipes:<br />
<br />
* [http://pasdoc.svn.sourceforge.net/viewvc/*checkout*/pasdoc/trunk/source/component/PasDoc_ProcessLineTalk.pas PasDoc_ProcessLineTalk.pas unit] implements TProcessLineTalk class, descendant of TProcess, that can be easily used to talk with any process on a line-by-line basis.<br />
<br />
* [http://pasdoc.svn.sourceforge.net/viewvc/*checkout*/pasdoc/trunk/source/component/PasDoc_Aspell.pas PasDoc_Aspell.pas units] implements TAspellProcess class, that performs spell-checking by using underlying TProcessLineTalk instance to execute aspell and communicate with running aspell process.<br />
<br />
Both units are rather independent from the rest of pasdoc sources, so they may serve as real-world examples of using TProcess to run and communicate through pipes with other program.<br />
<br />
----<br />
[[TXMLPropStorage]]</div>Amedeohttps://wiki.freepascal.org/index.php?title=Executing_External_Programs/it&diff=34099Executing External Programs/it2009-02-21T16:34:54Z<p>Amedeo: /* An Improved Example */</p>
<hr />
<div>{{Executing External Programs}}<br />
<br />
== Introduzione ==<br />
Ci sono molti modi di eseguire un programma esterno, ma questo articolo si focalizza solo su uno: [[doc:fcl/process/tprocess.html|TProcess]].<br />
Se usi solitamente '''ShellExecute''' e / o '''WinExec''' in Delphi, allora puoi iniziare ad usare TProcess come un'alternativa in FPC/Lazarus (Questo vale anche se usi usi Lazarus in Linux, perchè TProcess è cross-platform).<br />
<br />
'''Nota:''' FPC/Lazarus supporta '''ShellExecute''' e / o '''WinExec''', ma questo supporto è solo in Win32. Se vuoi programmare in 'cross-platform', allora usa TProcess, è la miglior scelta!<br />
<br />
<br />
== SysUtils.ExecuteProcess ==<br />
<br />
Il modo più semplice se non necessiti pipes ne ogni forma di controllo è di usare semplicemente SysUtils.ExecuteProcess('/percorso/completo/al/file/binario',['arg1','arg2']);<br />
<br />
<br />
== TProcess ==<br />
Puoi usare TProcess per lanciare programmi esterni.Alcuni benefici nell'uso di TProcess sono:<br />
<br />
*Piattaforma Indipendente<br />
*Capacità di leggere da stdout e scrivere in stdin.<br />
<br />
Nota: TProcess non è un terminal/shell! Non puoi eseguire direttamente scripts or redirigere output usando operatori tipo "|", ">", "<", "&" etc. Eì possibile ottenere gli stessi risultati con TProcess usando Pascal, qualche sempio è di seguito..<br />
<br />
Importante: Devi specificare il percorso completo all'eseguibile. Per esempio '/bin/cp' invece di 'cp'. Se il programma è nel percorso standard PATH allora puoi usare la funzione [[doc:lcl/fileutil/finddefaultexecutablepath.html|FindDefaultExecutablePath]] da [[doc:lcl/fileutil/index.html|FileUtil]] unit di LCL.<br />
<br />
=== Un semplice esempio ===<br />
<pascal><br />
// Questo è un programma dimostrativo che mostra come lanciare<br />
// un mprogramma esterno.<br />
program launchprogram;<br />
<br />
// Qui includiamo i files che hanno utilizzo funzionale<br />
// e le procedure che ci occorreranno.<br />
uses <br />
Classes, SysUtils, Process;<br />
<br />
// This is defining the var "AProcess" as a variable <br />
// of the type "TProcess"<br />
var <br />
AProcess: TProcess;<br />
<br />
// This is where our program starts to run<br />
begin<br />
// Now we will create the TProcess object, and<br />
// assign it to the var AProcess.<br />
AProcess := TProcess.Create(nil);<br />
<br />
// Tell the new AProcess what the command to execute is.<br />
// Let's use the FreePascal compiler<br />
AProcess.CommandLine := 'ppc386 -h';<br />
<br />
// We will define an option for when the program<br />
// is run. This option will make sure that our program<br />
// does not continue until the program we will launch<br />
// has stopped running. vvvvvvvvvvvvvv<br />
AProcess.Options := AProcess.Options + [poWaitOnExit];<br />
<br />
// Now that AProcess knows what the commandline is <br />
// we will run it.<br />
AProcess.Execute;<br />
<br />
// This is not reached until ppc386 stops running.<br />
AProcess.Free; <br />
end.<br />
</pascal><br />
Questo è quanto! Hai appena imparato come eseguire un programma esterno dall'interno del tuo stesso programma.<br />
<br />
=== Un esempio comprovato ===<br />
Che bello!, ma come leggo l' Output di un programma che ho eseguito ?<br />
<br />
Bene, espandiamo il nostro esempio cosi che otteniamo questo:<br />
<br />
<delphi><br />
// This is a demo program that shows how to launch<br />
// an external program and read from it's output.<br />
program launchprogram;<br />
<br />
// Here we include files that have useful functions<br />
// and procedures we will need.<br />
uses <br />
Classes, SysUtils, Process;<br />
<br />
// This is defining the var "AProcess" as a variable <br />
// of the type "TProcess"<br />
// Also now we are adding a TStringList to store the <br />
// data read from the programs output.<br />
var <br />
AProcess: TProcess;<br />
AStringList: TStringList;<br />
<br />
// This is where our program starts to run<br />
begin<br />
// Now we will create the TProcess object, and<br />
// assign it to the var AProcess.<br />
AProcess := TProcess.Create(nil);<br />
<br />
// Create the TStringList object.<br />
AStringList := TStringList.Create;<br />
<br />
// Tell the new AProcess what the command to execute is.<br />
// Let's use the FreePascal compiler<br />
AProcess.CommandLine := 'ppc386 -h';<br />
<br />
// We will define an option for when the program<br />
// is run. This option will make sure that our program<br />
// does not continue until the program we will launch<br />
// has stopped running. Also now we will tell it that<br />
// we want to read the output of the file.<br />
AProcess.Options := AProcess.Options + [poWaitOnExit, poUsePipes];<br />
<br />
// Now that AProcess knows what the commandline is <br />
// we will run it.<br />
AProcess.Execute;<br />
<br />
// This is not reached until ppc386 stops running.<br />
<br />
// Now read the output of the program we just ran<br />
// into the TStringList.<br />
AStringList.LoadFromStream(AProcess.Output);<br />
<br />
// Save the output to a file.<br />
AStringList.SaveToFile('output.txt');<br />
<br />
// Now that the file is saved we can free the <br />
// TStringList and the TProcess.<br />
AStringList.Free;<br />
AProcess.Free; <br />
end.<br />
</delphi><br />
<br />
=== Reading large output ===<br />
In the previous example we waited until the program exited. Then we read, what the program has written to its output. But suppose the program writes a lot of data to the output, the pipe becomes full and the called progam waits until the pipe has been read from. But the calling program doesn't read from it, until the called program has ended. A dead lock occurs.<br />
<br />
The following example therefore doesn't use poWaitOnExit, but reads from the output, while the program is still running. The output is stored in a memory stream, that can be used later to read the output into a TStringList.<br />
<br />
<delphi> program procoutlarge;<br />
{<br />
Copyright (c) 2004 by Marc Weustink<br />
<br />
This example is creeated in the hope that it will be useful,<br />
but WITHOUT ANY WARRANTY; without even the implied warranty of<br />
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.<br />
}<br />
<br />
uses<br />
Classes, Process, SysUtils;<br />
<br />
const<br />
READ_BYTES = 2048;<br />
<br />
var<br />
S: TStringList;<br />
M: TMemoryStream;<br />
P: TProcess;<br />
n: LongInt;<br />
BytesRead: LongInt;<br />
<br />
begin<br />
// We cannot use poWaitOnExit here since we don't<br />
// know the size of the output. On Linux the size of the<br />
// output pipe is 2 kB. If the output data is more, we <br />
// need to read the data. This isn't possible since we are <br />
// waiting. So we get a deadlock here.<br />
//<br />
// A temp Memorystream is used to buffer the output<br />
<br />
M := TMemoryStream.Create;<br />
BytesRead := 0;<br />
<br />
P := TProcess.Create(nil);<br />
P.CommandLine := 'ppc386 -va bogus.pp';<br />
P.Options := [poUsePipes];<br />
WriteLn('-- executing --');<br />
P.Execute;<br />
while P.Running do<br />
begin <br />
// make sure we have room<br />
M.SetSize(BytesRead + READ_BYTES);<br />
<br />
// try reading it<br />
n := P.Output.Read((M.Memory + BytesRead)^, READ_BYTES);<br />
if n > 0 <br />
then begin<br />
Inc(BytesRead, n);<br />
Write('.')<br />
end<br />
else begin <br />
// no data, wait 100 ms<br />
Sleep(100); <br />
end;<br />
end;<br />
// read last part<br />
repeat<br />
// make sure we have room<br />
M.SetSize(BytesRead + READ_BYTES);<br />
// try reading it<br />
n := P.Output.Read((M.Memory + BytesRead)^, READ_BYTES);<br />
if n > 0 <br />
then begin<br />
Inc(BytesRead, n);<br />
Write('.');<br />
end;<br />
until n <= 0;<br />
if BytesRead > 0 then WriteLn;<br />
M.SetSize(BytesRead); <br />
WriteLn('-- executed --');<br />
<br />
S := TStringList.Create;<br />
S.LoadFromStream(M);<br />
WriteLn('-- linecount = ', S.Count, ' --');<br />
for n := 0 to S.Count - 1 do<br />
begin<br />
WriteLn('| ', S[n]);<br />
end;<br />
WriteLn('-- end --');<br />
S.Free;<br />
P.Free;<br />
M.Free;<br />
end.</delphi><br />
<br />
=== Using input and output of a TProcess ===<br />
See processdemo example in the [https://lazarus-ccr.svn.sourceforge.net/svnroot/lazarus-ccr/examples/process Lazarus-CCR SVN].<br />
<br />
=== Hints on the use of TProcess ===<br />
If you are creating a cross-platform program, you can change commandline according to the OS, using directives "{$IFDEF}s" and "{$ENDIF}s".<br />
<br />
Example:<br />
<delphi> {...}<br />
AProcess:TProcess.Create(nil)<br />
{$IFDEF WIN32}<br />
AProcess.CommandLine := 'calc.exe'; //Windows Calc<br />
{$ENDIF}<br />
{$IFDEF LINUX}<br />
AProcess.CommandLine := 'kcalc'; //KDE Calc<br />
{$ENDIF}<br />
AProcess.Execute; //in alternative, you can use AProcess.Active:=True<br />
{...}</delphi><br />
<br />
=== Example of "talking" with aspell process ===<br />
<br />
Inside [http://pasdoc.sourceforge.net/ pasdoc] source code you can find two units that perform spell-checking by "talking" with running aspell process through pipes:<br />
<br />
* [http://pasdoc.svn.sourceforge.net/viewvc/*checkout*/pasdoc/trunk/source/component/PasDoc_ProcessLineTalk.pas PasDoc_ProcessLineTalk.pas unit] implements TProcessLineTalk class, descendant of TProcess, that can be easily used to talk with any process on a line-by-line basis.<br />
<br />
* [http://pasdoc.svn.sourceforge.net/viewvc/*checkout*/pasdoc/trunk/source/component/PasDoc_Aspell.pas PasDoc_Aspell.pas units] implements TAspellProcess class, that performs spell-checking by using underlying TProcessLineTalk instance to execute aspell and communicate with running aspell process.<br />
<br />
Both units are rather independent from the rest of pasdoc sources, so they may serve as real-world examples of using TProcess to run and communicate through pipes with other program.<br />
<br />
----<br />
[[TXMLPropStorage]]</div>Amedeohttps://wiki.freepascal.org/index.php?title=Executing_External_Programs/it&diff=34098Executing External Programs/it2009-02-21T16:32:41Z<p>Amedeo: /* Un semplice esempio */</p>
<hr />
<div>{{Executing External Programs}}<br />
<br />
== Introduzione ==<br />
Ci sono molti modi di eseguire un programma esterno, ma questo articolo si focalizza solo su uno: [[doc:fcl/process/tprocess.html|TProcess]].<br />
Se usi solitamente '''ShellExecute''' e / o '''WinExec''' in Delphi, allora puoi iniziare ad usare TProcess come un'alternativa in FPC/Lazarus (Questo vale anche se usi usi Lazarus in Linux, perchè TProcess è cross-platform).<br />
<br />
'''Nota:''' FPC/Lazarus supporta '''ShellExecute''' e / o '''WinExec''', ma questo supporto è solo in Win32. Se vuoi programmare in 'cross-platform', allora usa TProcess, è la miglior scelta!<br />
<br />
<br />
== SysUtils.ExecuteProcess ==<br />
<br />
Il modo più semplice se non necessiti pipes ne ogni forma di controllo è di usare semplicemente SysUtils.ExecuteProcess('/percorso/completo/al/file/binario',['arg1','arg2']);<br />
<br />
<br />
== TProcess ==<br />
Puoi usare TProcess per lanciare programmi esterni.Alcuni benefici nell'uso di TProcess sono:<br />
<br />
*Piattaforma Indipendente<br />
*Capacità di leggere da stdout e scrivere in stdin.<br />
<br />
Nota: TProcess non è un terminal/shell! Non puoi eseguire direttamente scripts or redirigere output usando operatori tipo "|", ">", "<", "&" etc. Eì possibile ottenere gli stessi risultati con TProcess usando Pascal, qualche sempio è di seguito..<br />
<br />
Importante: Devi specificare il percorso completo all'eseguibile. Per esempio '/bin/cp' invece di 'cp'. Se il programma è nel percorso standard PATH allora puoi usare la funzione [[doc:lcl/fileutil/finddefaultexecutablepath.html|FindDefaultExecutablePath]] da [[doc:lcl/fileutil/index.html|FileUtil]] unit di LCL.<br />
<br />
=== Un semplice esempio ===<br />
<pascal><br />
// Questo è un programma dimostrativo che mostra come lanciare<br />
// un mprogramma esterno.<br />
program launchprogram;<br />
<br />
// Qui includiamo i files che hanno utilizzo funzionale<br />
// e le procedure che ci occorreranno.<br />
uses <br />
Classes, SysUtils, Process;<br />
<br />
// This is defining the var "AProcess" as a variable <br />
// of the type "TProcess"<br />
var <br />
AProcess: TProcess;<br />
<br />
// This is where our program starts to run<br />
begin<br />
// Now we will create the TProcess object, and<br />
// assign it to the var AProcess.<br />
AProcess := TProcess.Create(nil);<br />
<br />
// Tell the new AProcess what the command to execute is.<br />
// Let's use the FreePascal compiler<br />
AProcess.CommandLine := 'ppc386 -h';<br />
<br />
// We will define an option for when the program<br />
// is run. This option will make sure that our program<br />
// does not continue until the program we will launch<br />
// has stopped running. vvvvvvvvvvvvvv<br />
AProcess.Options := AProcess.Options + [poWaitOnExit];<br />
<br />
// Now that AProcess knows what the commandline is <br />
// we will run it.<br />
AProcess.Execute;<br />
<br />
// This is not reached until ppc386 stops running.<br />
AProcess.Free; <br />
end.<br />
</pascal><br />
Questo è quanto! Hai appena imparato come eseguire un programma esterno dall'interno del tuo stesso programma.<br />
<br />
=== An Improved Example ===<br />
That's nice, but how do I read the Output of a program that I have run?<br />
<br />
Well, let's expand our example a little and do just that:<br />
<br />
<delphi><br />
// This is a demo program that shows how to launch<br />
// an external program and read from it's output.<br />
program launchprogram;<br />
<br />
// Here we include files that have useful functions<br />
// and procedures we will need.<br />
uses <br />
Classes, SysUtils, Process;<br />
<br />
// This is defining the var "AProcess" as a variable <br />
// of the type "TProcess"<br />
// Also now we are adding a TStringList to store the <br />
// data read from the programs output.<br />
var <br />
AProcess: TProcess;<br />
AStringList: TStringList;<br />
<br />
// This is where our program starts to run<br />
begin<br />
// Now we will create the TProcess object, and<br />
// assign it to the var AProcess.<br />
AProcess := TProcess.Create(nil);<br />
<br />
// Create the TStringList object.<br />
AStringList := TStringList.Create;<br />
<br />
// Tell the new AProcess what the command to execute is.<br />
// Let's use the FreePascal compiler<br />
AProcess.CommandLine := 'ppc386 -h';<br />
<br />
// We will define an option for when the program<br />
// is run. This option will make sure that our program<br />
// does not continue until the program we will launch<br />
// has stopped running. Also now we will tell it that<br />
// we want to read the output of the file.<br />
AProcess.Options := AProcess.Options + [poWaitOnExit, poUsePipes];<br />
<br />
// Now that AProcess knows what the commandline is <br />
// we will run it.<br />
AProcess.Execute;<br />
<br />
// This is not reached until ppc386 stops running.<br />
<br />
// Now read the output of the program we just ran<br />
// into the TStringList.<br />
AStringList.LoadFromStream(AProcess.Output);<br />
<br />
// Save the output to a file.<br />
AStringList.SaveToFile('output.txt');<br />
<br />
// Now that the file is saved we can free the <br />
// TStringList and the TProcess.<br />
AStringList.Free;<br />
AProcess.Free; <br />
end.<br />
</delphi><br />
<br />
=== Reading large output ===<br />
In the previous example we waited until the program exited. Then we read, what the program has written to its output. But suppose the program writes a lot of data to the output, the pipe becomes full and the called progam waits until the pipe has been read from. But the calling program doesn't read from it, until the called program has ended. A dead lock occurs.<br />
<br />
The following example therefore doesn't use poWaitOnExit, but reads from the output, while the program is still running. The output is stored in a memory stream, that can be used later to read the output into a TStringList.<br />
<br />
<delphi> program procoutlarge;<br />
{<br />
Copyright (c) 2004 by Marc Weustink<br />
<br />
This example is creeated in the hope that it will be useful,<br />
but WITHOUT ANY WARRANTY; without even the implied warranty of<br />
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.<br />
}<br />
<br />
uses<br />
Classes, Process, SysUtils;<br />
<br />
const<br />
READ_BYTES = 2048;<br />
<br />
var<br />
S: TStringList;<br />
M: TMemoryStream;<br />
P: TProcess;<br />
n: LongInt;<br />
BytesRead: LongInt;<br />
<br />
begin<br />
// We cannot use poWaitOnExit here since we don't<br />
// know the size of the output. On Linux the size of the<br />
// output pipe is 2 kB. If the output data is more, we <br />
// need to read the data. This isn't possible since we are <br />
// waiting. So we get a deadlock here.<br />
//<br />
// A temp Memorystream is used to buffer the output<br />
<br />
M := TMemoryStream.Create;<br />
BytesRead := 0;<br />
<br />
P := TProcess.Create(nil);<br />
P.CommandLine := 'ppc386 -va bogus.pp';<br />
P.Options := [poUsePipes];<br />
WriteLn('-- executing --');<br />
P.Execute;<br />
while P.Running do<br />
begin <br />
// make sure we have room<br />
M.SetSize(BytesRead + READ_BYTES);<br />
<br />
// try reading it<br />
n := P.Output.Read((M.Memory + BytesRead)^, READ_BYTES);<br />
if n > 0 <br />
then begin<br />
Inc(BytesRead, n);<br />
Write('.')<br />
end<br />
else begin <br />
// no data, wait 100 ms<br />
Sleep(100); <br />
end;<br />
end;<br />
// read last part<br />
repeat<br />
// make sure we have room<br />
M.SetSize(BytesRead + READ_BYTES);<br />
// try reading it<br />
n := P.Output.Read((M.Memory + BytesRead)^, READ_BYTES);<br />
if n > 0 <br />
then begin<br />
Inc(BytesRead, n);<br />
Write('.');<br />
end;<br />
until n <= 0;<br />
if BytesRead > 0 then WriteLn;<br />
M.SetSize(BytesRead); <br />
WriteLn('-- executed --');<br />
<br />
S := TStringList.Create;<br />
S.LoadFromStream(M);<br />
WriteLn('-- linecount = ', S.Count, ' --');<br />
for n := 0 to S.Count - 1 do<br />
begin<br />
WriteLn('| ', S[n]);<br />
end;<br />
WriteLn('-- end --');<br />
S.Free;<br />
P.Free;<br />
M.Free;<br />
end.</delphi><br />
<br />
=== Using input and output of a TProcess ===<br />
See processdemo example in the [https://lazarus-ccr.svn.sourceforge.net/svnroot/lazarus-ccr/examples/process Lazarus-CCR SVN].<br />
<br />
=== Hints on the use of TProcess ===<br />
If you are creating a cross-platform program, you can change commandline according to the OS, using directives "{$IFDEF}s" and "{$ENDIF}s".<br />
<br />
Example:<br />
<delphi> {...}<br />
AProcess:TProcess.Create(nil)<br />
{$IFDEF WIN32}<br />
AProcess.CommandLine := 'calc.exe'; //Windows Calc<br />
{$ENDIF}<br />
{$IFDEF LINUX}<br />
AProcess.CommandLine := 'kcalc'; //KDE Calc<br />
{$ENDIF}<br />
AProcess.Execute; //in alternative, you can use AProcess.Active:=True<br />
{...}</delphi><br />
<br />
=== Example of "talking" with aspell process ===<br />
<br />
Inside [http://pasdoc.sourceforge.net/ pasdoc] source code you can find two units that perform spell-checking by "talking" with running aspell process through pipes:<br />
<br />
* [http://pasdoc.svn.sourceforge.net/viewvc/*checkout*/pasdoc/trunk/source/component/PasDoc_ProcessLineTalk.pas PasDoc_ProcessLineTalk.pas unit] implements TProcessLineTalk class, descendant of TProcess, that can be easily used to talk with any process on a line-by-line basis.<br />
<br />
* [http://pasdoc.svn.sourceforge.net/viewvc/*checkout*/pasdoc/trunk/source/component/PasDoc_Aspell.pas PasDoc_Aspell.pas units] implements TAspellProcess class, that performs spell-checking by using underlying TProcessLineTalk instance to execute aspell and communicate with running aspell process.<br />
<br />
Both units are rather independent from the rest of pasdoc sources, so they may serve as real-world examples of using TProcess to run and communicate through pipes with other program.<br />
<br />
----<br />
[[TXMLPropStorage]]</div>Amedeohttps://wiki.freepascal.org/index.php?title=Executing_External_Programs/it&diff=34094Executing External Programs/it2009-02-21T15:26:13Z<p>Amedeo: /* SysUtils.ExecuteProcess */</p>
<hr />
<div>== Introduzione ==<br />
Ci sono molti modi di eseguire un programma esterno, ma questo articolo si focalizza solo su uno: [[doc:fcl/process/tprocess.html|TProcess]].<br />
Se usi solitamente '''ShellExecute''' e / o '''WinExec''' in Delphi, allora puoi iniziare ad usare TProcess come un'alternativa in FPC/Lazarus (Questo vale anche se usi usi Lazarus in Linux, perchè TProcess è cross-platform).<br />
<br />
'''Nota:''' FPC/Lazarus supporta '''ShellExecute''' e / o '''WinExec''', ma questo supporto è solo in Win32. Se vuoi programmare in 'cross-platform', allora usa TProcess, è la miglior scelta!<br />
<br />
<br />
== SysUtils.ExecuteProcess ==<br />
<br />
Il modo più semplice se non necessiti pipes ne ogni forma di controllo è di usare semplicemente SysUtils.ExecuteProcess('/percorso/completo/al/file/binario',['arg1','arg2']);<br />
<br />
<br />
== TProcess ==<br />
Puoi usare TProcess per lanciare programmi esterni.Alcuni benefici nell'uso di TProcess sono:<br />
<br />
*Piattaforma Indipendente<br />
*Capacità di leggere da stdout e scrivere in stdin.<br />
<br />
Nota: TProcess non è un terminal/shell! Non puoi eseguire direttamente scripts or redirigere output usando operatori tipo "|", ">", "<", "&" etc. Eì possibile ottenere gli stessi risultati con TProcess usando Pascal, qualche sempio è di seguito..<br />
<br />
Importante: Devi specificare il percorso completo all'eseguibile. Per esempio '/bin/cp' invece di 'cp'. Se il programma è nel percorso standard PATH allora puoi usare la funzione [[doc:lcl/fileutil/finddefaultexecutablepath.html|FindDefaultExecutablePath]] da [[doc:lcl/fileutil/index.html|FileUtil]] unit di LCL.<br />
<br />
=== Un semplice esempio ===<br />
<pascal><br />
// Questo è un programma dimostrativo che mostra come lanciare<br />
// un mprogramma esterno.<br />
program launchprogram;<br />
<br />
// Qui includiamo i files che hanno utilizzo funzionale<br />
// e le procedure che ci occorreranno.<br />
uses <br />
Classes, SysUtils, Process;<br />
<br />
// This is defining the var "AProcess" as a variable <br />
// of the type "TProcess"<br />
var <br />
AProcess: TProcess;<br />
<br />
// This is where our program starts to run<br />
begin<br />
// Now we will create the TProcess object, and<br />
// assign it to the var AProcess.<br />
AProcess := TProcess.Create(nil);<br />
<br />
// Tell the new AProcess what the command to execute is.<br />
// Let's use the FreePascal compiler<br />
AProcess.CommandLine := 'ppc386 -h';<br />
<br />
// We will define an option for when the program<br />
// is run. This option will make sure that our program<br />
// does not continue until the program we will launch<br />
// has stopped running. vvvvvvvvvvvvvv<br />
AProcess.Options := AProcess.Options + [poWaitOnExit];<br />
<br />
// Now that AProcess knows what the commandline is <br />
// we will run it.<br />
AProcess.Execute;<br />
<br />
// This is not reached until ppc386 stops running.<br />
AProcess.Free; <br />
end.<br />
</pascal><br />
<br />
That's it! You have just learned how to run an external program from inside your own program.<br />
<br />
=== An Improved Example ===<br />
That's nice, but how do I read the Output of a program that I have run?<br />
<br />
Well, let's expand our example a little and do just that:<br />
<br />
<delphi><br />
// This is a demo program that shows how to launch<br />
// an external program and read from it's output.<br />
program launchprogram;<br />
<br />
// Here we include files that have useful functions<br />
// and procedures we will need.<br />
uses <br />
Classes, SysUtils, Process;<br />
<br />
// This is defining the var "AProcess" as a variable <br />
// of the type "TProcess"<br />
// Also now we are adding a TStringList to store the <br />
// data read from the programs output.<br />
var <br />
AProcess: TProcess;<br />
AStringList: TStringList;<br />
<br />
// This is where our program starts to run<br />
begin<br />
// Now we will create the TProcess object, and<br />
// assign it to the var AProcess.<br />
AProcess := TProcess.Create(nil);<br />
<br />
// Create the TStringList object.<br />
AStringList := TStringList.Create;<br />
<br />
// Tell the new AProcess what the command to execute is.<br />
// Let's use the FreePascal compiler<br />
AProcess.CommandLine := 'ppc386 -h';<br />
<br />
// We will define an option for when the program<br />
// is run. This option will make sure that our program<br />
// does not continue until the program we will launch<br />
// has stopped running. Also now we will tell it that<br />
// we want to read the output of the file.<br />
AProcess.Options := AProcess.Options + [poWaitOnExit, poUsePipes];<br />
<br />
// Now that AProcess knows what the commandline is <br />
// we will run it.<br />
AProcess.Execute;<br />
<br />
// This is not reached until ppc386 stops running.<br />
<br />
// Now read the output of the program we just ran<br />
// into the TStringList.<br />
AStringList.LoadFromStream(AProcess.Output);<br />
<br />
// Save the output to a file.<br />
AStringList.SaveToFile('output.txt');<br />
<br />
// Now that the file is saved we can free the <br />
// TStringList and the TProcess.<br />
AStringList.Free;<br />
AProcess.Free; <br />
end.<br />
</delphi><br />
<br />
=== Reading large output ===<br />
In the previous example we waited until the program exited. Then we read, what the program has written to its output. But suppose the program writes a lot of data to the output, the pipe becomes full and the called progam waits until the pipe has been read from. But the calling program doesn't read from it, until the called program has ended. A dead lock occurs.<br />
<br />
The following example therefore doesn't use poWaitOnExit, but reads from the output, while the program is still running. The output is stored in a memory stream, that can be used later to read the output into a TStringList.<br />
<br />
<delphi> program procoutlarge;<br />
{<br />
Copyright (c) 2004 by Marc Weustink<br />
<br />
This example is creeated in the hope that it will be useful,<br />
but WITHOUT ANY WARRANTY; without even the implied warranty of<br />
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.<br />
}<br />
<br />
uses<br />
Classes, Process, SysUtils;<br />
<br />
const<br />
READ_BYTES = 2048;<br />
<br />
var<br />
S: TStringList;<br />
M: TMemoryStream;<br />
P: TProcess;<br />
n: LongInt;<br />
BytesRead: LongInt;<br />
<br />
begin<br />
// We cannot use poWaitOnExit here since we don't<br />
// know the size of the output. On Linux the size of the<br />
// output pipe is 2 kB. If the output data is more, we <br />
// need to read the data. This isn't possible since we are <br />
// waiting. So we get a deadlock here.<br />
//<br />
// A temp Memorystream is used to buffer the output<br />
<br />
M := TMemoryStream.Create;<br />
BytesRead := 0;<br />
<br />
P := TProcess.Create(nil);<br />
P.CommandLine := 'ppc386 -va bogus.pp';<br />
P.Options := [poUsePipes];<br />
WriteLn('-- executing --');<br />
P.Execute;<br />
while P.Running do<br />
begin <br />
// make sure we have room<br />
M.SetSize(BytesRead + READ_BYTES);<br />
<br />
// try reading it<br />
n := P.Output.Read((M.Memory + BytesRead)^, READ_BYTES);<br />
if n > 0 <br />
then begin<br />
Inc(BytesRead, n);<br />
Write('.')<br />
end<br />
else begin <br />
// no data, wait 100 ms<br />
Sleep(100); <br />
end;<br />
end;<br />
// read last part<br />
repeat<br />
// make sure we have room<br />
M.SetSize(BytesRead + READ_BYTES);<br />
// try reading it<br />
n := P.Output.Read((M.Memory + BytesRead)^, READ_BYTES);<br />
if n > 0 <br />
then begin<br />
Inc(BytesRead, n);<br />
Write('.');<br />
end;<br />
until n <= 0;<br />
if BytesRead > 0 then WriteLn;<br />
M.SetSize(BytesRead); <br />
WriteLn('-- executed --');<br />
<br />
S := TStringList.Create;<br />
S.LoadFromStream(M);<br />
WriteLn('-- linecount = ', S.Count, ' --');<br />
for n := 0 to S.Count - 1 do<br />
begin<br />
WriteLn('| ', S[n]);<br />
end;<br />
WriteLn('-- end --');<br />
S.Free;<br />
P.Free;<br />
M.Free;<br />
end.</delphi><br />
<br />
=== Using input and output of a TProcess ===<br />
See processdemo example in the [https://lazarus-ccr.svn.sourceforge.net/svnroot/lazarus-ccr/examples/process Lazarus-CCR SVN].<br />
<br />
=== Hints on the use of TProcess ===<br />
If you are creating a cross-platform program, you can change commandline according to the OS, using directives "{$IFDEF}s" and "{$ENDIF}s".<br />
<br />
Example:<br />
<delphi> {...}<br />
AProcess:TProcess.Create(nil)<br />
{$IFDEF WIN32}<br />
AProcess.CommandLine := 'calc.exe'; //Windows Calc<br />
{$ENDIF}<br />
{$IFDEF LINUX}<br />
AProcess.CommandLine := 'kcalc'; //KDE Calc<br />
{$ENDIF}<br />
AProcess.Execute; //in alternative, you can use AProcess.Active:=True<br />
{...}</delphi><br />
<br />
=== Example of "talking" with aspell process ===<br />
<br />
Inside [http://pasdoc.sourceforge.net/ pasdoc] source code you can find two units that perform spell-checking by "talking" with running aspell process through pipes:<br />
<br />
* [http://pasdoc.svn.sourceforge.net/viewvc/*checkout*/pasdoc/trunk/source/component/PasDoc_ProcessLineTalk.pas PasDoc_ProcessLineTalk.pas unit] implements TProcessLineTalk class, descendant of TProcess, that can be easily used to talk with any process on a line-by-line basis.<br />
<br />
* [http://pasdoc.svn.sourceforge.net/viewvc/*checkout*/pasdoc/trunk/source/component/PasDoc_Aspell.pas PasDoc_Aspell.pas units] implements TAspellProcess class, that performs spell-checking by using underlying TProcessLineTalk instance to execute aspell and communicate with running aspell process.<br />
<br />
Both units are rather independent from the rest of pasdoc sources, so they may serve as real-world examples of using TProcess to run and communicate through pipes with other program.<br />
<br />
----<br />
[[TXMLPropStorage]]</div>Amedeohttps://wiki.freepascal.org/index.php?title=Executing_External_Programs/it&diff=34093Executing External Programs/it2009-02-21T15:15:15Z<p>Amedeo: /* Introduzione */</p>
<hr />
<div>== Introduzione ==<br />
Ci sono molti modi di eseguire un programma esterno, ma questo articolo si focalizza solo su uno: [[doc:fcl/process/tprocess.html|TProcess]].<br />
Se usi solitamente '''ShellExecute''' e / o '''WinExec''' in Delphi, allora puoi iniziare ad usare TProcess come un'alternativa in FPC/Lazarus (Questo vale anche se usi usi Lazarus in Linux, perchè TProcess è cross-platform).<br />
<br />
'''Nota:''' FPC/Lazarus supporta '''ShellExecute''' e / o '''WinExec''', ma questo supporto è solo in Win32. Se vuoi programmare in 'cross-platform', allora usa TProcess, è la miglior scelta!<br />
<br />
<br />
== SysUtils.ExecuteProcess ==<br />
<br />
Il modo più semplice se non necessiti pipes ne ogni forma di controllo è di usare semplicemente SysUtils.ExecuteProcess('/percorso/completo/al/file/binario',['arg1','arg2']);</div>Amedeohttps://wiki.freepascal.org/index.php?title=Executing_External_Programs/it&diff=34092Executing External Programs/it2009-02-21T15:12:04Z<p>Amedeo: /* Introduzione */</p>
<hr />
<div>== Introduzione ==<br />
Ci sono molti modi di eseguire un programma esterno, ma questo articolo si focalizza solo su uno: [[doc:fcl/process/tprocess.html|TProcess]].<br />
Se usi solitamente '''ShellExecute''' e / o '''WinExec''' in Delphi, allora puoi iniziare ad usare TProcess come un'alternativa in FPC/Lazarus (Questo vale anche se usi usi Lazarus in Linux, perchè TProcess è cross-platform).<br />
<br />
'''Nota:''' FPC/Lazarus supporta '''ShellExecute''' e / o '''WinExec''', ma questo supporto è solo in Win32. Se vuoi programmare in 'cross-platform', allora usa TProcess, è la miglior scelta!</div>Amedeohttps://wiki.freepascal.org/index.php?title=Overview_of_Free_Pascal_and_Lazarus/it&diff=33857Overview of Free Pascal and Lazarus/it2009-02-14T14:50:40Z<p>Amedeo: </p>
<hr />
<div>{{Overview of Free Pascal and Lazarus}}<br />
[[category:Italiano]]<br />
<br />
Free Pascal (FPC) è un compilatore Pascal con due notevoli caratteristiche: un alto grado di compatibilità con DELPHI e la disponibilità per una varietà di piattaforme, incluso Windows, Mac OS X, e Linux. La compatibilità di Free Pascal con Delphi include non solo il supporto per gli stessi programmi orientati agli oggetti che usa Deplhi, ma anche per molte delle stesse librerie di potenti ruotines e classi per le quali Delphi è conosciuto. Ciò include units familiari quali System, SysUtils, StrUtils, DateUtils, Classes, Variants, Math, IniFiles and Registry, che sono incluse con Free Pascal su tutte le piattaforme supportate. Free Pascal include inoltre units come Windows, ShellAPI, BaseUnix, Unix and DynLibs per gli accessi specifici ad ogni sistema operativo supportato. Queste dozzine è più di units costituiscono il il core di cio che solitamente si intende per Free Pascal run-time library (RTL).<br />
<br />
Lazarus è una sistema di sviluppo open source per compilare e costruire programmi mediante il compilatore Free Pascal con l'aggiunta di un sistema di sviluppo integrato (IDE) che include un editor di codice con evidenziatore di sintassi e un disegnatore di moduli , così come un libreria di componenti altamente compatibile con Delphi's Visual Component Library (VCL).Lazarus Component Library (LCL) include gli equivalenti per molti dei familiari controlli VCL quali moduli , tasti, caselle di testo e così via, che sono usate per creare applicazioni dotate di Interfacce grafiche utente GUI.<br />
<br />
Sia Free Pascal che Lazarus sono scritti in PASCAL. Il codice sorgente completo è disponibile non solo per il compilatore Free Pascal e LAZARUS IDE , ma anche per tutte le unità che costituiscono Free Pascal RTL e Lazarus LCL.<br />
<br />
Come Delphi anche Free Pascal e Lazarus sono entrambi strumenti di programmazione ad orientamento generico, ciò significa che con essi si possono sviluppare ampie varietà di programmi incluso i seguenti:<br />
<br />
== Applicazioni per Terminale (Console) ==<br />
<br />
<br />
Le applicazioni per terminale non hanno una GUI. Esse sono normalmente lanciate dalla console, leggono i loro input alla console, scrivono i loro output nella console. In windows la console è il prompt dei comandi ( finestra dos). In OS X e Linux la console è la finestra Terminale. Le applicazioni per console comprendono cose tipo piccole utilità quali in Windows FC ( comparazione di files) oppure i comandi cp e cd in unix/linux. Le applicazioni da terminale possono inoltre essere potenti applicazioni numeriche, modelli,o gestioni di dati che non necessitano ingombranti GUI in quanto esse sono lanciate da altri programmi o mediante batch o script o dalla IDE Lazarus.<br />
Si possono creare Applicazioni per Terminale mediante nient'altro che un semplice editor di testo e il compilatore Free Pascal. Non è necessario usare Lazarus per svilupparle. Tuttavia se preferite lavorare in un sistema integrato, potete usare Lazarus per creare progetti per Applicazioni Console quindi compilarne il codice in Lazarus IDE.<br />
<br />
== DLL Dynamically loadable libraries ==<br />
<br />
Una DLL o libreria caricabile dinamicamente è normalmente una collezione di funzioni compilate che possono essere richiamate da altri programmi. Come il nome suggerisce , la libreria non è collegata all'interno dell'eseguibile al momento della compilazione, ma è invece caricata al momento dell'esecuzione del programma. In windows una file libreria ha una estensione .dll. In OS X, un file libreria ha un'estensione .dylib (dynamic shared library). In Linux un file libreria ha un'estensione .so ( shared object library). Le Librerie caricabili dinamicamente sono tipicamente usate per sviluppare add-ons per altri programmi, per sviluppare librerie che possono essere richiamate da programmi scritti in altri linguaggi quali C e C++, o per suddividere grossi progetti in parti in modo da non dover ricompilare ciascuna altra parte ( programmazione ad oggetti). Windows stesso è composto da migliaia di dll cosi come altre grosse applicazioni quali OpenOffice.org.<br />
<br />
Come per le applicazioni per Console è necessario solo un editor di testo a il compilatore Free Pascal per sviluppare una libreria, tuttavia si possono creare progetti di librerie mediante Lazarus.<br />
<br />
In windows le dll hanno la reputazione di essere complesse e di instabili.This has more to do with the way they've sometimes been installed than it does with DLLs themselves. Actually, since passing information to and from DLLs is normally done with standard, simple data types (rather than with language-specific objects or structures), this requirement forces programmers to pay more attention to what they're doing. If done right, this can result in better, more stable programs. <br />
<br />
<br />
== Applicazioni con interfaccia grafica utente GUI ==<br />
La maggior parte dei programmi che usiamo quotidianamente sono applicazioni GUI, inclusi i word processor, i WEB browser, i fogli elettronici, e molti strumenti di sviluppo. Lazarus e Delphi sono ottimi esempi di complete applicazioni GUI. Quando sviluppiamo una applicazione GUI con Lazarus non solo sviluppiamo units di codice PASCAL , ma disegniamo anche moduli contenenti controlli visivi quali tasti e caselle di scelta. Come con Delphi i moduli creati con Lazarus sono creati in modo visivo. Le proprietà dei controlli possono essere settate mediante IDE o mediante scrittura di codice.<br />
<br />
Dal momento in cui i controlli LCL sono disponibili in tutte le piattaforme supportate, una applicazione GUI sviluppata in una piattaforma ( per esempio Windows) può essere ricompilata in un'altra piattaforma ( per esempio LINUX o OS X ) senza dover fare cambiamenti al disegno dei moduli o dei files di codice.<br />
<br />
{{AutoCategory}}<br />
<br />
<br />
----<br />
[[Lazarus Tutorial]]</div>Amedeohttps://wiki.freepascal.org/index.php?title=Overview_of_Free_Pascal_and_Lazarus&diff=33850Overview of Free Pascal and Lazarus2009-02-14T10:13:58Z<p>Amedeo: </p>
<hr />
<div>{{Overview of Free Pascal and Lazarus}}<br />
[[Overview of Free Pascal and Lazarus/it]]<br />
<br />
Free Pascal (FPC) is an open-source Pascal compiler with two notable features: a high degree of [[Delphi]] compatibility and availability on a variety of platforms, including Windows, Mac OS X, and Linux. Free Pascal's compatibility with Delphi includes not only support for the same Object Pascal programming language that Delphi uses, but also for many of the same libraries of powerful routines and classes that Delphi is justly known for. This includes familiar units such as System, SysUtils, StrUtils, DateUtils, Classes, Variants, Math, IniFiles and Registry, which are included with Free Pascal on all supported platforms. Free Pascal also includes units such as Windows, ShellAPI, BaseUnix, Unix and DynLibs for accessing features specific to an operating system. These dozen or so units make up the core of what is usually referred to as the Free Pascal run-time library (RTL).<br />
<br />
Lazarus is an open-source development system that builds on the Free Pascal compiler by adding an integrated development environment (IDE) that includes a syntax-highlighting code editor and visual form designer, as well as a component library that's highly compatible with Delphi's Visual Component Library (VCL). The Lazarus Component Library (LCL) includes equivalents for many of the familiar VCL controls such as forms, buttons, text boxes and so on that are used to create applications that have a graphical user interface (GUI).<br />
<br />
Both Free Pascal and Lazarus are written in Pascal. Complete source code is available not only for the Free Pascal compiler and Lazarus IDE, but also for all units that make up the Free Pascal RTL and Lazarus LCL.<br />
<br />
Like Delphi, Free Pascal and Lazarus are both general-purpose programming tools, meaning you can develop a wide variety of programs with them, including the following:<br />
<br />
=== Console applications ===<br />
<br />
Console apps don't have a GUI. Instead they are usually launched from the console, read their input from the console, and write their output to the console. In Windows the console is usually referred to as a command prompt window. In OS X and Linux the console is referred to as a terminal window. Console apps include things like small utilities such as the Windows FC (file compare) program or the Unix cd and cp commands. Console apps can also be powerful number crunching, modeling, or data processing programs that don't need a fancy GUI because they're started by other programs or from batch files (or shell scripts on unix/linux). The Free Pascal compiler and the utility programs included with it are all console apps, meaning they can be run from the console, a batch file, or from the Lazarus IDE.<br />
<br />
You can create a console app with no more than a text editor and the Free Pascal compiler. You don't have to use Lazarus to develop console apps. However, if you prefer to work in an integrated environment, you can use Lazarus to create a project for the console app and then edit and compile the code in the Lazarus IDE.<br />
<br />
=== Dynamically loadable libraries === <br />
A dynamically loadable library is usually a collection of compiled functions that can be called by other programs. As the name suggests, the library is not linked into your executable at compile-time, but instead is loaded at run-time. In Windows, a library file has a .dll extension (dynamic-link library, or DLL). In OS X, a library file has a .dylib extension (dynamic shared library). In Linux, a library file has an .so extension (shared object library). Dynamically loadable libraries are typically used to develop add-ons for other programs, to develop libraries that can be called by programs written in other languages such as C and C++, or to partition large projects into chunks so that the project's developers don't step on each other's toes. Windows itself is made up of hundreds of DLLs, as are many other large applications such as OpenOffice.org.<br />
<br />
Like console apps, you only need a text editor and the Free Pascal compiler to develop a library, although you can also create a Lazarus project for the library and develop the library in the Lazarus IDE.<br />
<br />
On Windows, DLLs have an undeserved reputation for being overly complex and unstable. This has more to do with the way they've sometimes been installed than it does with DLLs themselves. Actually, since passing information to and from DLLs is normally done with standard, simple data types (rather than with language-specific objects or structures), this requirement forces programmers to pay more attention to what they're doing. If done right, this can result in better, more stable programs.<br />
<br />
=== GUI apps ===<br />
<br />
Most of the programs we use daily are GUI apps, including word processors, Web browsers, spreadsheet programs, even many development tools. Lazarus and Delphi are both good examples of full-featured GUI apps. When developing a GUI app with Lazarus, not only do you develop units of Pascal code, you also design forms containing visual controls such as buttons and list boxes. Like Delphi, form design in Lazarus is done visually. Control properties can be set in the IDE or in code.<br />
<br />
Since the LCL controls are available on all supported platforms, a GUI app developed on one platform (for example, Windows) can be compiled on another platform (for example, OS X or Linux) without any changes to the form design or the form code files.<br />
<br />
----<br />
[[Lazarus Tutorial]]</div>Amedeo