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

From Free Pascal wiki
Jump to navigationJump to search
Line 104: Line 104:
 
<div class="floatright">[[Image:Source_FormWithButton1.png‎ ]]</div>
 
<div class="floatright">[[Image:Source_FormWithButton1.png‎ ]]</div>
  
== Object-Oriented Extensions to standard Pascal ==
+
== Объектно-ориентированное расширение стандартного Pascal ==
  
The Pascal record structure is extended by defining an
+
Структура Pascal "Запись" расширена определением
 
=== Object ===
 
=== Object ===
  
Line 195: Line 195:
 
*'''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.
 
*'''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.
 
*'''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 ==
 
== Further information ==

Revision as of 11:20, 7 October 2009

Template:Object Oriented Programming with FreePascal and Lazarus

Существует много отличных учебников по Pascal, но этот служит попыткой вести начинающего программиста далее, в объектно-ориентированное программирование ( Object-Oriented Programming, )являющееся расширением стандартного Pascal, применяемое в Turbo-pascal, Delphi и FreePascal/Lazarus.

Object (Объект) - это расширение стандартной структуры Pascal record (Запись).

Стандартное текстовое программирование на Pascal пригодно для создания приложений, которые, как обычные приложения Unix, очень хорошо выполняют всего одну функцию. Программа может выполнять и очень сложные действия, предлагая пользователю выборы из меню, но по существу ограничена командами, которые пользователь набирает на клавиатуре и смотрит ответы на терминале или принтере.

Для создания графического интерфейса пользователя Graphical User Interface (GUI) обычно применяются методы объектно-ориентированного программирования (чаще всего на C или его вариантах, или Visual Basic, или на одном из OO вариантов Pascal, таких, как FreePascal совместно с Lazarus, или без него).

На GUI потребителю предоставляется экран с множеством картинок, отображающих определенную структуру, содержащую набор инструментов, или Widgets (Виджетов), ассоциированных с различными действиями, таких как

  • Выбор из меню,
  • Открытие или сохранение файлов,
  • Соединение с Интернет,
  • Выполнение вычислений, и т.п.

Пользователь перемещает по экрану указатель мыши или иного инструмента выбора точки для выбора действия, выполняемого в ответ на щелчок мыши или нажатие клавиши.

Программы со сложным графическим интерфейсом могут быть написаны на стандартном Pascal или любом другом языке программирования, но намного проще применить объектно-ориентированную систему, в которой каждый графический объект на экране может иметь собственный набор свойств, процедур и функций, существующих совместно, в общей структуре.


Объекты - аналогия реального мира

Объекты напоминают результаты анализа крови из больницы или поликлиники.

Анализ крови

Экземпляр анализа - несомненно, объект; он имеет много связанной информации, документов и других физических объектов.

  • Трубка для анализа, определенного типа, который заказал врач.
  • Отдельные правила (или методика, способ выполнения) для указания медсестре, берущей анализ.
    • какой тип трубки применить,
    • как произвести отбор анализа,
    • как хранить его до передачи в лабораторию.
  • Этикетка на трубке с указанием
    • номера анализа
    • имени пациента и даты рождения
    • даты и времени взятия
    • требуемых проверок.
  • Бланк запроса для лаборатории, указывающий
    • Номер анализа
    • Номер запроса врача
    • что предусматривает запрос врача и
    • дается более полная информация о пациенте
    • возможный диагноз, которому нужно подтверждение.

Копия запроса помещается в карточку пациента для напоминания врачу об ожидании результата в соответствующее время.

  • В лабораторию - отдельные методы для указания
    • как производить анализ,
    • какую применять аппаратуру,
    • как откалибровать и произвести замеры на приборе,
    • как результаты должны быть отображены и
    • направлены врачу.

Фактически результаты - запись, помогающая врачу установить диагноз, и ее копия помещается в карточку пациента.

Физическая доза крови может быть оставлена на хранение для контроля или дальнейших проверок, может быть слита в раковину, или сожжена; это также должно быть описано.

Однако в жизни для врача нет необходимости описывать по буквам все детали и инструкции для каждого анализа; действительно, он может иметь немного понятий об обработке анализа в лаборатории. Детали разных процессов унаследованы от предшествующих анализов - имеется общий план для всей последовательности - и мы можем представить анализ крови с его документами, данными и основными методами, как комплекс объект.

В уме врача анализ крови выглядит в большей степени, как его результат, для медсестры - как доза крови, трубка, этикетка и условия хранения; а по сути - это единый объект.

Другой пример - автомобиль

Если Вас пугает пример с кровью, те же рассуждения могут быть приложены к автомобилю, сданному в гараж для ремонта.

Он может состоять из:

  • физической автомашины
  • документов владельца: регистрации или лицензии (включая номерной знак), страхового свидетельства, денег для покупки частей, оплаты ремонта и т.д.
  • информации о потреблении топлива
  • документов водителей, управлявших машиной, с их частными лицензиями
  • записей об обслуживании, хранящихся в гараже
  • описаний способов или процедур для обычной проверки и эксплуатации
  • способов более сложного ремонта и т.д.
  • выписанного счета для клиента

Пример программирования

Достаточно этих введений с примерами из реального мира! Обратимся к основной цели - программированию на FreePascal.

Рассмотрим создание простой формы с несколькими элементами управления для приложения на FreePascal/Lazarus.

ObjectInspector-TForm.png
BlankForm.png

Вначале Lazarus IDE представляет программисту шаблон пустой формы, на которой можно размещать различные элементы управления, или объекты.

Предоставленный бланк уже является объектом, со своими свойствами, такими как Позиция (Верх и Отступ), размер (Высота и Ширина), цвет, шрифт для текста и т.д.



Если на форму поместить кнопку (тип TButton), она будет иметь свой набор свойств, который можно просмотреть в окне Инспектора Объектов.

Некоторые свойства кнопки имеют те же имена, что и свойства формы, что является следствием Наследования многих свойств из общего класса - предка, указывающего, как свойства определяются и управляются в классе - потомке.

Как и для свойств, Инспектор Объектов имеет вкладку, называемую События, дающую возможность настроить реакцию объекта на внешние воздействия, такие как щелчок мыши на кнопке (OnClick), или некоторое изменение позиции, размера, или других свойств (OnChange), для того, чтобы приложение выполняло в ответ некоторые действия.

Физический образ кнопки на форме, совместно с его свойствами и методами обработки событий считается единой сущностью, или Объектом в Pascal.

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

Объектно-ориентированное расширение стандартного Pascal

Структура Pascal "Запись" расширена определением

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