Monday, January 21, 2013

Implementing roles in domain models - Role object pattern


It is a common scenario in domain modeling to implement roles such as Manager, Salesman, and Engineer etc. in the applications, which are basically subclasses of a common role player class such as an Employee. However, this means that different instances of the role classes are actually different objects with different state and different identity, even if they are meant to represent the same logical entity.

At first glance it sounds like a case for inheritance, but there are complications as the same object may show multiple behavior or can make changes to another role during its lifetime. For e.g. an Engineer may become an Architect or a Manager in the organization. The expectation is to have a model where a class could be seen as more than one concept or role, and where attributes specific to one of those concepts can be specified.

The Role Object Pattern addresses this problem by representing an object and its roles as a composition of one role player object and arbitrarily many role objects. The role class model provides the flexibility of the association with role-specific attributes and even class operations, if needed.

Using the role object pattern the above problem statement can be addressed like


The employee class defines methods for managing roles via the RoleObject abstraction. The common superclasses for employee specific roles are provided by the EmployeeRole class. The concrete implementations for the EmployeeRole like Engineer, Salesman or Manager define and implement the interface for specific roles. The role objects are instantiated at runtime and added to the employee to add operations specific the role.

[TestClass]
public class EngineerRoleTests
{
    private Employee _employee;

    [TestInitialize]
    public void Initialize()
    {
        _employee = new Employee("Prajeesh Prathap");
        _employee.AddRole(new Engineer());
    }

    [TestMethod]
    public void CanRetrieveARoleFromAnObjectAtALaterPoint()
    {
        var manager = _employee.GetRoleOf<Engineer>();
        Assert.IsNotNull(manager);
    }
}

1 comment:

Anonymous said...

I have read sso mwny articleѕ about thе blogger lοvers except this pаrаgraph іs reallу
a faѕtidiοus post, kеep itt uρ.


Alsο νisit mу homеpаgе: ERRO: A URL requisitada não pôde ser recuperada