프로퍼티

프로퍼티 (Properties)

전역 블록(global block)에서도 클래스 안에서처럼 프로퍼티를 선언할 수 있어요. 차이는 전역 프로퍼티는 클래스 인스턴스가 필요 없다는 점이에요. 이 프로퍼티의 인스턴스는 하나뿐이니까요. 그 외에는 전역 프로퍼티도 클래스 프로퍼티처럼 동작합니다. 전역 프로퍼티의 읽기/쓰기 지정자도 메서드가 아니라 일반 프로시저여야 해요.

출처: Properties

본문

전역 프로퍼티 개념은 Free Pascal 고유의 기능이라 Delphi에는 없어요. 프로퍼티를 다루려면 ObjFPC 모드가 필요합니다.

전역 프로퍼티는 값이 저장된 위치를 '숨기거나', 값을 그때그때 계산하거나, 프로퍼티에 쓰이는 값을 검사하는 용도로 쓸 수 있어요.

예시를 볼게요.

{$mode objfpc}
unit testprop;

Interface

Function GetMyInt : Integer;
Procedure SetMyInt(Value : Integer);

Property
  MyProp : Integer Read GetMyInt Write SetMyInt;

Implementation

Uses sysutils;

Var
  FMyInt : Integer;

Function GetMyInt : Integer;
begin
  Result:=FMyInt;
end;

Procedure SetMyInt(Value : Integer);
begin
  If ((Value mod 2)=1) then
    Raise Exception.Create('MyProp can only contain even value');
  FMyInt:=Value;
end;

end.

읽기/쓰기 지정자를 다른 유닛에 숨길 수도 있어요. 유닛의 uses 절에 포함되어야 하는 다른 유닛에 지정자를 선언하면 되죠. 이렇게 하면 클래스의 private 섹션처럼 프로그래머로부터 읽기/쓰기 접근 지정자를 숨길 수 있어요. 앞선 예시를 이렇게 바꿔 볼 수 있어요.

{$mode objfpc}
unit testrw;

Interface

Function GetMyInt : Integer;
Procedure SetMyInt(Value : Integer);

Implementation

Uses sysutils;

Var
  FMyInt : Integer;

Function GetMyInt : Integer;
begin
  Result:=FMyInt;
end;

Procedure SetMyInt(Value : Integer);
begin
  If ((Value mod 2)=1) then
    Raise Exception.Create('Only even values are allowed');
  FMyInt:=Value;
end;

end.

그러면 testprop 유닛은 이렇게 됩니다.

{$mode objfpc}
unit testprop;

Interface

uses testrw;

Property
  MyProp : Integer Read GetMyInt Write SetMyInt;

Implementation

end.

프로퍼티에 대한 더 자세한 내용은 6장(294쪽)에서 다뤄요.

더 알아보기