MATLAB Object-Oriented Programming

(Joyce) #1

Represent State with Enumerations


The MachineState class defines two enumeration members to represent the state of a
machine, either running or not running.


classdef MachineState
enumeration
Running
NotRunning
end
end


The Machine class represents a machine with start and stop operations. The
MachineState enumerations are easy to work with because of their eq and char
methods, and they result in code that is easy to read.


classdef Machine < handle
properties (SetAccess = private)
State = MachineState.NotRunning
end


methods
function start(machine)
if machine.State == MachineState.NotRunning
machine.State = MachineState.Running;
end
disp (machine.State.char)
end
function stop(machine)
if machine.State == MachineState.Running
machine.State = MachineState.NotRunning;
end
disp (machine.State.char)
end
end
end


Create a Machine object and call start and stop methods


m = Machine;
m.start


Running


m.stop


Mutable Handle vs. Immutable Value Enumeration Members
Free download pdf