0
一个假设的场景来问我的问题:如何在Matlab中将类实例作为句柄传递
假设我们有2个实体:老板和员工。当员工完成工作时,他/她想让人们知道。在这种情况下,老板'种'订阅该消息并决定要做什么
我实现了这个接口,它具有任何其他类可以实现的抽象方法。在这个(因为他/她将决定他/她想要做什么):
classdef (Abstract) Interface < handle
methods
getJobsCompleted(n)
end
end
老板类继承接口和实现方法getJobsCompleted()
classdef Boss < Interface & handle
properties
myEmployee
end
methods
function this = Boss()
this.myEmployee = Employee(this)
this.myEmployee.doJobs();
end
%My boss implements (i.e. decides what to do) the abstract method
function getJobsCompleted(n)
%DO SOMETHING with n
end
end
end
最后,员工执行工作并通知老板。
classdef Employee < handle
properties
numJobsCompleted;
boss = [];%pointer or reference to Boss instance
end
methods
function this = Employee(myBoss)
this.boss = myBoss; %reference/pointer to my boss so I know who to notify
end
function doJobs()
%% do something then let boss know
this.numJobsCompleted = 40;
this.boss.getJobsCompleted(this.numJobsCompleted);
end
end
end
我一直试图失败的做法是将一个引用传递给Employee类,以便他/她知道要通知哪位老板。
即
in Boss
this.myEmployee = Employee(this)