简体   繁体   English

如何使用Interface引用保护匿名类创建

[英]How to protect anonymous class creation with Interface reference

Consider the Business Scenario: 考虑业务场景:

We have student Interface with payFees() method. 我们有student界面与payFees()方法。 There are some classes which implements student interface and implement payFees method. 有一些类实现了学生界面并实现了payFees方法。 These are : SchoolStudent , CollegeStudent , UniversityStudent , OnlineStudent . 这些是: SchoolStudentCollegeStudentUniversityStudentOnlineStudent

Now a developer will create the list of student as List<Student> and add different students to the list ( SchoolStudent , CollegeStudent etc.). 现在,开发人员将创建学生List<Student>作为List<Student> ,并将不同的学生添加到列表中( SchoolStudentCollegeStudent等)。 Now developer can create anonymous class using Student interface, implements some faulty payFees method and add that object to the studentlist. 现在开发人员可以使用Student接口创建匿名类,实现一些错误的payFees方法并将该对象添加到studentlist。 This anonymous student is not valid and it will distrub the business logic. 这个匿名学生无效,它会分散业务逻辑。

So how we will protect developer from creating anonymous class of Student interface. 那么我们如何保护开发人员不要创建匿名的Student接口类。

One way I can think of is (assuming all the valid implementations of Student interface are in the same package) to define a package private additional interface (let's call it ValidStudent ) that the valid implementations implement in addition to implementing Student . 我能想到的一种方法是(假设Student接口的所有有效实现都在同一个包中)来定义一个包私有附加接口(让我们称之为ValidStudent ),除了实现Student之外,有效的实现还会实现。 That package private interface doesn't have to contain any methods. 该包私有接口不必包含任何方法。

Then, you can have some code that validates the Student instances added to the List - that validation code will check that those instances also implement the ValidStudent interface. 然后,您可以使用一些代码来验证添加到ListStudent实例 - 验证代码将检查这些实例是否也实现了ValidStudent接口。 Any custom implementations of Student won't pass that validation. Student任何自定义实现都不会通过该验证。

package x;
public interface Student
{
    ...
}

package x;
interface ValidStudent // package private
{
    // nothing here
}

package x;
public class SchoolStudent implements Student, ValidStudent
{

}

And an example for the validation (the validation can be done by any class in package x that does something with Student instances) : 并且验证的一个例子(验证可以由包x中的任何类与Student实例一起完成):

package x;
public class StudentValidator
{
    public static boolean isValid (Student student) 
    {
        return student instanceof ValidStudent;
    }
}

您可以使用不是Student接口,而是使用具有包访问构造函数的Student类。

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

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