0

What is the best solution for situation:

class Person
...
class Student extends Person
...  
class Employee extends Person
...
class Visitor extends Person
...

And some person is employee and student, for example. Classical approach of inheritance isn't good solution.

I can use delegation pattern:

User {
   Person p.
   Collection<Role> roles; 
}

And All classes : Student, Employee, Visitor - will implement Role interface or class.

Is it a good solution?

Thank you!

1
  • 1
    Objects can't change their types, but people can change their roles. So the answer should be clear. Commented Dec 14, 2014 at 11:06

1 Answer 1

3

Usually, the delegation pattern you suggest is a good idea. It has a lot of advantages over multiple inheritance:

  1. It is supported by every language; multiple inheritance support differs from language to language and your language of choice might even have none at all.
  2. The roles of a person do not have to be known at compile time.
  3. You can adjust the roles at run time! A person may quit being a student or enrole as a student. Easy case with delegation, impossible with multiple inheritance
  4. No combinatorical explosion: Consider you have ten roles. If any combination of roles was possible, you would need 2^10 = 1024 classes. Have fun with that.

So, stick to the delegation! Delegation is a wonderful thing and the answer to many questions in OOP :).

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.