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)