Этот пример показывает, как задать Систему object™ конструктор и позволить ей принимать пары свойства значения имени, как введено.
Задайте конструктора Системного объекта, который является методом, который имеет то же имя как класс (MyFile в этом примере). В рамках того метода вы используете метод setProperties, чтобы сделать все общественные собственности доступными для входного параметра, когда пользователь создает объект. nargin является функцией MATLAB®, которая определяет количество входных параметров. varargin указывает на все общественные собственности объекта.
methods function obj = MyFile(varargin) setProperties(obj,nargin,varargin{:}); end end
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 while the
% object is running.
properties (Nontunable)
Filename ="default.bin" % the name of the file to create
Access = 'wb' % The file access character vector (write, binary)
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
% You call setProperties in the constructor to let
% a user specify public properties of object as
% name-value pairs.
function obj = MyFile(varargin)
setProperties(obj,nargin,varargin{:});
end
end
methods (Access = protected)
% In setup allocate any resources, which in this case is
% opening the file.
function setupImpl(obj)
obj.pFileID = fopen(obj.Filename,obj.Access);
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