Difference between revisions of "Object Oriented Programming with Free Pascal and Lazarus/it"

From Lazarus wiki
Jump to navigationJump to search
Line 70: Line 70:
  
  
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à.
+
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à.
  
 
Traduzione da completare.....
 
Traduzione da completare.....

Revision as of 12:08, 31 March 2009

Template:Object Oriented Programming with FreePascal and Lazarus

Esistono molte guide eccellenti su Pascal, ma questa guida tenta di coinvolgere ulteriormente il principiante , nella programmazione orientata agli oggetti o Object-Oriented Programming, che è un'estensione dello standard pascal, offerta da Turbo pascal, Delphi e FreePascal/Lazarus.

Un Object è un'estensione della struttura standard pascal detta record

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.

Ciò che un programma fa può essere un'azione veramente complicata ,e può offrire all'utente molte opzioni di menu, ma è essenzialmente ristretta ad obbedire a comandi che l'utente digita da tastiera e a listare le sue risposte sul terminale o sulla stampante.

Per poter produrre una Graphical User Interface (GUI) usualmente si utilizza una sorta di Metodo di programmazione orientata agli oggetti (spesso facendo uso di C o di una delle sue varianti, o Visual Basic, o una delle OO varianti di Pascal quali FreePascal con o senza Lazarus).

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 Widgets che sono associati con varie azioni quali

  • selezioni da menu,
  • aperture o salvataggio files ,
  • connessioni ad Internet,
  • esecuzioni di calcoli numerici, etc.

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.

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.


Oggetti - una analogia con il mondo reale

Consideriamo le analogie di un campione di sangue prelevato in un ospedale o in uno studio medico.

Campione di sangue

Il campione fisico è certamente un oggetto o object; ed ha , associato con esso una quantità di informazioni,documenti ed altri oggetti fisici.

  • Provetta, del tipo determinato dal test che si dovrà eseguire.
  • Metodica (o metodo, procedura operativa standard) utilizzata dall'infermiera o dal tecnico di laboratorio che prelevano e processano il campione
    • che tipo di provetta si dovrà usare,
    • come processare il campione
    • come conservarlo prima di consegnarlo al laboratorio.
  • Etichetta sulla provetta con i dettagli per
    • identificare il campione
    • Nome e cognome e data di nascita del paziente
    • data e ora del prelievo
    • analisi richieste.
  • Modulo di richiesta che accompagna il campione per il laboratorio cui il campione è diretto
    • ID Campione
    • ID del medico richiedente
    • quali analisi il medico richiede e
    • anamnesi e dettagli completi del paziente
    • La possibile diagnosi di cui si richiede conferma.


Una copia delle richiesta viene conservata nella cartella clinica per ricordare al medico di attendersi risultati entro un periodo di tempo adeguato.


  • In laboratorio - metodi locali per determinare
    • come il campione deve essere analizzato,
    • Quale strumento usare,
    • come lo strumento dovrà operare e come dovrà essere calibrato,
    • come il risultato dovrà essere memorizzato formattato e
    • presentato al medico.

L'effettivo 'risultato' è un dato che il medico usa per formulare la diagnosi, e una copia dei risultati è archiviata nella cartella clinica del paziente.

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.


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.

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.


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à.

Traduzione da completare.....

Another Example - Automobile

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:

  • the physical vehicle
  • documents held by the owner: registration or license (including license plates), insurance, receipts for purchase, parts, repairs etc
  • the fuel consumption history
  • the drivers allowed to use the vehicle, with their license particulars
  • service records held by the garage
  • methods or procedures to be followed for routine checking and maintenance
  • methods to be followed for non-routine repairs etc
  • billing information for the customer

Programming Example

Enough of this pre-occupation with Real-World examples! Let us proceed to the main purpose: programming in FreePascal.

Let us consider the creation of a simple Form with a few controls for an application in FreePascal/Lazarus.

ObjectInspector-TForm.png
BlankForm.png

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.

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.



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.

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.

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).

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.

ObjectInspector-TButton.png
FormWithButton.png
Source FormWithButton1.png

Object-Oriented Extensions to standard Pascal

The Pascal record structure is extended by defining an

Object

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.

For example, an object could contain an array of real values, together with a Method for calculating the average.

Type
  Average = Object
    NumVal: Integer;
    Values: Array [1..200] of Real;
    Function Mean: Real; { calculates the average value of the array }
  End;

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.

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.

Class

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.

Here is a simple example of a typical Class declaration:

{-----------------------------------------}
{example of Class declaration from the LCL}
{-----------------------------------------}
 TPen = class(TFPCustomPen)
 private
   FColor: TColor;
   FPenHandleCached: boolean;
   FReference: TWSPenReference;
   procedure FreeReference;
   function GetHandle: HPEN;
   function GetReference: TWSPenReference;
   procedure ReferenceNeeded;
   procedure SetHandle(const Value: HPEN);
 protected
   procedure DoAllocateResources; override;
   procedure DoDeAllocateResources; override;
   procedure DoCopyProps(From: TFPCanvasHelper); override;
   procedure SetColor
        (const NewColor: TColor; const NewFPColor: TFPColor); virtual;
   procedure SetFPColor(const AValue: TFPColor); override;
   procedure SetColor(Value: TColor);
   procedure SetMode(Value: TPenMode); override;
   procedure SetStyle(Value: TPenStyle); override;
   procedure SetWidth(value: Integer); override;
 public
   constructor Create; override;
   destructor Destroy; override;
   procedure Assign(Source: TPersistent); override;
   property Handle: HPEN read GetHandle write SetHandle; deprecated;
   property Reference: TWSPenReference read GetReference;
 published
   property Color: TColor read FColor write SetColor default clBlack;
   property Mode default pmCopy;
   property Style default psSolid;
   property Width default 1;
 end;


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

  • 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.
  • 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
  • public - this means that items defined here are available to any programming unit that includes the current unit in its Uses clause
  • 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.

Methods

A method is just like a standard procedure or function, but can have some additional directives.

Some of the methods defined above are labelled with the directive virtual; others are labelled with the override directive.

  • 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.
  • 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.

Methods with no virtual or override directive are static methods (the usual kind in Pascal). Those with a virtual or override directive are dynamic.

Special instances of methods are:

  • create - a constructor for a class, which takes care of allocating memory, collecting together all the information needed and configuring/initializing the various properties.
  • 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.

Properties

Properties are just like ordinary fields in a conventional Pascal record, but they can have read and/or write specifiers.

  • 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.
  • 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.
  • 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.


Further information

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)

--Kirkpatc 11:04, 20 July 2008 (CEST)


Console Mode Pascal