简体   繁体   中英

How to protect anonymous class creation with Interface reference

Consider the Business Scenario:

We have student Interface with payFees() method. There are some classes which implements student interface and implement payFees method. These are : 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.). Now developer can create anonymous class using Student interface, implements some faulty payFees method and add that object to the 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.

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 . 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. Any custom implementations of Student won't pass that validation.

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) :

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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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