Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Which Design Pattern should I use to model a Person-Role relationship?

I just couldn't figure out which design pattern I should adopt here. Say I have class like this:

class Person

String role;

public void takeRole(String role) {
  this.role = role;
}

public void do() {

  switch(role)

    case a:
      do this and that;
      this.role = b;

    case b:
      do this and that;

    case c:
      do this and that;
      this.role=a;

    ....

In short, a Person has roles and do() method depends on on what his role is. In some cases, he may have to switch roles. I think this do() should be abstracted (more so because there may be other roles defined in the future)---but how? Should there be a Role class?

Any help will be appreciated.

Edit:

Thanks for sparing your time, people. I'd like to add one more thing. I did think (at least as an idea) many of the suggested solutions. Here are are my difficulties: If I subclass Person class (such as PersonTypeA, personTypeB, etc., and assign each particular role to the appropriate person type, then I have a difficulty when switching roles (for instance, an engineer becomes an accountant!---Weird, to say the least.

On the other hand, if I create classes for each role; then (1) a role does not feel like an object, because (at least in my case) a role does not have attributes but only method(s). Consequently, role_A_1 is no different than role_A_2. But for each person I'll have to create a new role object---even if they both share the same role.

I'm not sure if I made myself clear and I'm not sure if my points make sense at all.

like image 572
blackened Avatar asked Dec 04 '22 23:12

blackened


1 Answers

Not in a design pattern way, but more in a logical way:

Instead of having a huge 'if role is this, do that, else if it's this' statement, some kind of Role class with a DoThis() method would be easier.

A Person has-a Role. A Person can DoThis() and that the Role then also can DoThis().

Rather than a Person saying what they do according to the Role, the Role says what they can do.

like image 92
The Communist Duck Avatar answered Dec 08 '22 16:12

The Communist Duck