プロパティの初期化と 1 度限りの計算の設定
この例では、System object™ の初期化と設定を行うコードの作成方法を示します。
この例では、ファイルを開いてファイル リソースを割り当て、System object がそのファイルに書き込めるようにします。こうした初期化の作業はオブジェクトを実行するたびに行うのではなく、設定中に 1 回だけ行います。
初期化するパブリック プロパティの定義
この例では、パブリックの Filename プロパティを定義し、このプロパティの値を調整不可能な文字ベクトル default.bin として指定します。setup メソッドの呼び出し後は、"調整不可能な" プロパティは変更できません。
properties (Nontunable) Filename = "default.bin" end
初期化するプライベート プロパティの定義
"プライベート" のプロパティには直接アクセスできず、System object のメソッドを通じてのみ可能です。この例では、pFileID プロパティをプライベート プロパティとして定義します。また、このプロパティを "非表示" として定義し、ユーザーには表示されない内部プロパティであることを示します。
properties (Hidden,Access = private)
pFileID;
end設定の定義
設定と初期化作業は、setupImpl メソッドを使用して行います。1 回限りの実行コードは setupImpl メソッドに含めます。setupImpl メソッドは、オブジェクトをはじめて実行するときに一度呼び出されます。この例では、バイナリ データを書き込むために、ファイルを開いてファイル リソースを割り当てます。
methods function setupImpl(obj) obj.pFileID = fopen(obj.Filename,"wb"); if obj.pFileID < 0 error("Opening the file failed"); end end end
設定手順には含まれていませんが、ファイルを使用したコード作成の終了後、ファイルは閉じてください。releaseImpl メソッドを使用してリソースを解放します。
初期化および設定をもつ完全なクラス定義ファイル
classdef MyFile < matlab.System
% MyFile write numbers to a file
% These properties are nontunable. They cannot be changed
% after the setup method has been called or the object
% is running.
properties (Nontunable)
Filename = "default.bin" % the name of the file to create
end
% These properties are private. Customers can only access
% these properties through methods on this object
properties (Hidden,Access = private)
pFileID; % The identifier of the file to open
end
methods (Access = protected)
% In setup allocate any resources, which in this case
% means opening the file.
function setupImpl(obj)
obj.pFileID = fopen(obj.Filename,'wb');
if obj.pFileID < 0
error("Opening the file failed");
end
end
% This System object writes the input to the file.
function stepImpl(obj,data)
fwrite(obj.pFileID,data);
end
% Use release to close the file to prevent the
% file handle from being left open.
function releaseImpl(obj)
fclose(obj.pFileID);
end
end
end参考
setupImpl | releaseImpl | stepImpl