简体   繁体   English

面向对象设计的专业化和泛化

[英]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 目前我们正在开发与帐户和权限相关的东西

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} 我们是应该为学生和教师创建两个单独的课程,还是为一个名为Account的单个课程创建一个帐户类型属性,该属性可以是枚举{student,teacher,admin}

To follow OO design to 100%: A student is not a teacher. 按照OO设计100%:学生不是老师。 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. 如果没有区别,只需坚持使用Account类和type属性来说明它们是什么类型的用户。

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. 如果要遵循.NET安全模型,则应将StudentTeacher添加为角色,并使用Thread.CurrentPrincipal.IsInRole("teacher")检查其权限。

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 解决方案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";
}

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). 你可以创建一个Person类,并为Student和Teacher创建子类,并将模型Account作为一个单独的类,它可以有以下任何一个:1)一个属性,它只说明它属于哪个(哪个Person对象)2)一个属性说它是属于老师还是学生,或3)拥有一个表示账户特权​​的位置的财产(假设个人持有的特权是账户之间唯一的区别因素)。 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. 这里提到的每种方法都有自己的优点和缺点。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM