specialization and generalization in Object oriented design
We are building a social networking website for students and teachers. and currently we are working on Accounts and permissions related stuff
开发者_JAVA百科Should we make a two seperate classes for Student and teachers or a single class named Account and have a Account type property which can be a enum {student, teacher , admin}
You could create a class Person and have subclasses for Student and Teacher and model Account as a separate class which could have either one of these: 1) a property that just says to whom (which Person object) it belongs to 2) a property that says whether it belongs to a teacher or to a student or 3) a property that holds a bitset that signifies the privileges the account has (assuming the privileges held by the individual is the only differentiating factor between accounts). How you would want to go about it would really depend on the kind of features you would want to support. Each of the approach mentioned here has its own pros and cons.
To follow OO design to 100%: A student is not a teacher. Both are persons.
But it all depends on what they should be able to do. If there are no difference, just stick with a Account
class and a type
property saying what kind of users they are.
If you want to follow .NET security model you should instead add Student and Teacher as roles and use Thread.CurrentPrincipal.IsInRole("teacher")
to check their privileges.
Update
Solution one
Use a flag enum.
[Flags]
public enum AccountType
{
Guest,
User,
Teacher = 2,
Admin = 4
}
public class Account
{
public bool IsTeacher
{
get { return (user.AccountType & AccountType.Teacher) != 0; }
}
public int AccounType {get;set;}
}
var teacherAndAdmin = AccountType.Teacher + AccountType.Admin;
Solution 2
Use a roles array (and a seperate table). Load all roles into the account:
public class Account
{
private List<string> _roles = new List<string>();
public void IsTeacher
{
get { return _roles.Contains(AccountRoles.Teacher); }
}
}
public static class AccountRoles
{
public const string Teacher = "Teacher";
}
精彩评论