How do you model a role in object orientation?

2

Some things are not very clear to me these days.

How do you normally model a role in object orientation?

It's through a composition, right? For example, to model that a% of performs the role of a Pessoa or Cliente , it is modeled that Person has Fornecedor , or a Cliente , etc.

How is this in the UML? And in the code?

How does delegation (forwarding ) work in this story? ( See example )

    
asked by anonymous 01.09.2018 / 15:40

2 answers

1

Very simplified:

class Pessoa {
    string Nome;
}
class Cliente {
    Pessoa pessoa;
    decimal credito;
}
class Faturamento {
    Venda(Cliente cliente) => Write(cliente.pessoa.Nome);
}

If you want someone to be aware of the roles he or she can play in two ways:

class Pessoa {
    string Nome;
    Cliente cliente;
    Fornecedor fornecedor;
}

Each role you add needs to change the class, which violates some principles, but that is not always a problem.

Another way:

enum TipoPapel { Cliente, Fornecedor }
class Pessoa {
    string Nome;
    List<(TipoPapel, IPapel)> papeis = new();
    AdicionaPapel(TipoPapel tipo, Ipapel papel) => papeis.Add((tipo, papel));
}

Instead of enum could use string which can make it easier or more difficult, depending on the case. You could use a dictionary instead of the list, or another structure, even more specialized. And you could use a specific type instead of the tuple. You could have control of the roles in a separate type that abstracted the list.

UML is one of the most trolling things I've ever seen, so do not:)

    
06.09.2018 / 14:01
1

Copy of Maniero's response, only in pseudo-Java, to better visualize (and take boilerplate .

Very simplified:

public class Pessoa {
    private String nome;
}

public interface Papel {
    void umMetodo();
}

public class Cliente implements Papel {
    private Pessoa pessoa;
    private BigDecimal credito;
}

public class Faturamento {
    public void venda(Cliente cliente) {
        System.out.println(cliente.getPessoa().getNome());
    }
}

If you want someone to be aware of the roles he or she can play in two ways:

public class Pessoa {
    private String nome;
    private Cliente cliente;
    private Fornecedor fornecedor;
}

Each role you add needs to change the class, which violates some principles, but that is not always a problem.

Another way:

public enum TipoPapel { Cliente, Fornecedor }

public class Pessoa {
    private String Nome;
    private Map<TipoPapel, Papel> papeis = new HashMap<>();

    public void adicionaPapel(TipoPapel tipo, Papel papel) {
        papeis.put(tipo, papel);
    }
}

Instead of enum could use String that can make it easier or difficult, depending on the case. He could use another structure, even more specialized, instead of the map. You could have control of the roles in a separate type that abstracted the map.

    
06.09.2018 / 15:49