开发者

inheritance and roles

开发者 https://www.devze.com 2023-03-17 22:25 出处:网络
Let\'s use a quite plain example with employees and company(-ies). public abstract class Employee { // bunch of its features

Let's use a quite plain example with employees and company(-ies).

public abstract class Employee
{
    // bunch of its features
}

public sealed class SalesManager : Employee
{
}

public sealed class SEO : Employee
{
}

Employee can take different posts or play different roles. So using inheritance (maybe with factory patterns in addition) doesn't give such a flexibility for concrete employee instance to change its role.

What would you advice, unfortunately I haven't seen the kind of approaches yet. And I haven't met a book which lights up the problem.

Edit

Thank you guys! In my edit I wanted to ask one more thing. Using gener开发者_高级运维ic role is it possible to transfer such a BLL to DAL. I have heard that generics are not supported in Entity Framework??

Thanks!


Use a has-a relationship

public class Employee 
{
    public Role EmployeeRole { get; set; }
}

public enum Role 
{
    SalesManager,
    SalesPerson
}

Or you can make Role a class to store additional information in addition to the name of their role.

public class Role
{
    public string Name { get; set; }
    public decimal BaseSalary { get; set; }
}

To illustrate @Aasmund Eldhuset's comment:

public abstract class Role
{
    public string Name { get; set; }
    public decimal BaseSalary { get; set; }

    public abstract void PerformRole();
}

public class SalesPerson : Role
{
    public void PerformRole()
    {
        // Do something
    }
}


Running with the idea of using a class, you can make it generic:

abstract class EmployeeRole { } 

or

interface EmployeeRole { }

And have different types inherit from this abstraction:

class CEO : EmployeeRole { }

class SalesMgr : EmployeeRole { }

class Employee<T> where T : EmployeeRole
{

}

Then have a generic Factory implementation:

public Employee<T> MakeEmployee<T>() where T : EmployeeRole
{

}
0

精彩评论

暂无评论...
验证码 换一张
取 消