What design pattern should be used to model Person-Role relationships?

I just could not figure out which design template I should accept here. Let's say I have a class as follows:

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 the do () method depends on what his role is. In some cases, he may have to switch roles. I think this () should be abstracted (especially since there may be other roles in the future) --- but how? Should there be a role class?

Any help would be appreciated.

Edit:

, , . . ( , ) . : Person (, PersonTypeA, personTypeB ..) , (, ! --- , .

, ; (1) , ( , ) , (). , role_A_1 role_A_2. , .

, , , .

+3
7

, :

, , , , , - DoThis() .

. DoThis() DoThis().

, , , , .

+7

State Pattern. , - :

interface Role {
    public void doRole(Context context);
}

class RoleA implements Role {
    public void doRole(Context context) {
        // do this and that
        context.setRole(new RoleB());
    }
}

class RoleB implements Role {
    public void doRole(Context context) {
        // do that and this
        context.setRole(new RoleA());
    }
}

class Context {
    private Role _role;

    public Context() {
        // set initial role
        setRole(new RoleA());
    }

    public void setRole(Role newRole) { _role = newRole; }

    public doSomething() {
        _role.doRole(this);
    }
}

, Context, Role . , . , , Role setRole() .

+5

Coad Domain-Neutral:

http://www.petercoad.com/download/bookpdfs/jmcuch01.pdf

, , ( ). , , - , .

.

+1

0

do,

interface Action {
    void do()
}

a Map<String, Action>, , , actionMap.get(role). do() actionMap.get(role).do()

0

I would say that the role of HAS-A Person. I would have a Role interface whose particular implementation would wrap Person and decorate it with any new features that I need.

public interface Role
{
    Person getPerson();
    void action(); // might need more here
};

public class Person
{
   // whatever fields you need
}

public class Admin
{
    private Person person;

    public Admin(Person p) { this.person = person; }

    public void action() { } // some some admin stuff.
}
0
source

Source: https://habr.com/ru/post/1789825/


All Articles