[英]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
. 这些是: SchoolStudent
, CollegeStudent
, UniversityStudent
, OnlineStudent
。
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>
,并将不同的学生添加到列表中( SchoolStudent
, CollegeStudent
等)。 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. 然后,您可以使用一些代码来验证添加到List
的Student
实例 - 验证代码将检查这些实例是否也实现了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.