初始化属性并设置一次性计算
此示例说明如何编写代码以初始化并设置 System object™。
在此示例中,通过打开相应文件以使 System object 写入该文件来分配文件资源。您可以在设置时一次性执行这些初始化任务,而不是在每次运行对象时执行。
定义要初始化的公共属性
在此示例中,您会定义公共的 Filename 属性,并将该属性的值指定为不可调的字符向量 default.bin。调用 setup 方法之后,用户便无法更改不可调属性。
properties (Nontunable) Filename = "default.bin" end
定义要初始化的私有属性
用户无法直接访问私有属性,而只能通过 System object 的方法来访问。在此示例中,您将 pFileID 属性定义为私有属性。此外,还将此属性定义为隐藏属性,以指示它是一个内部属性,从不会对用户显示。
properties (Hidden,Access = private)
pFileID;
end定义设置
您可以使用 setupImpl 方法来执行设置和初始化任务。您应在 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