2016-09-16 55 views
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) 

回答

1

这将工作,你只需要明确接受对象实例作为输入参数的所有方法。您需要更新以下两个函数的定义:

function doJobs(this) 
function getJobsCompleted(this, n) 

话虽这么说,这样做的更好的办法可能是使用events and listeners。然后,您会让员工发出“JobCompleted”事件,让老板为所有员工倾听这些事件。这可以防止员工需要跟踪他们的老板。

classdef Boss < handle 

    properties 
     Employees 
     Listeners 
    end 

    methods 
     function this = Boss(employees) 
      this.Employees = employees; 

      this.Listeners = addlistener(employees, 'JobCompleted', @this.onJobCompleted); 
     end 

     function onJobCompleted(this, employee, evnt) 
      fprintf('%s completed a job!\n', employee.Name); 
     end 
    end 
end 

Employee.m

classdef Employee < handle 

    properties 
     Name 
     CompletedJobs = 0 
    end 

    events 
     JobCompleted 
    end 

    methods 
     function this = Employee(name) 
      this.Name = name; 
     end 

     function doJob(this) 
      this.CompletedJobs = this.CompletedJobs + 1; 
      notify(this, 'JobCompleted') 
     end 
    end 
end 

而且使用它像:

employees(1) = Employee('Fred'); 
employees(2) = Employee('Bill'); 

boss = Boss(employees); 

doJob(employees); 
doJob(employees(1)); 
相关问题