簡體   English   中英

如何使用Interface引用保護匿名類創建

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

考慮業務場景:

我們有student界面與payFees()方法。 有一些類實現了學生界面並實現了payFees方法。 這些是: SchoolStudentCollegeStudentUniversityStudentOnlineStudent

現在,開發人員將創建學生List<Student>作為List<Student> ,並將不同的學生添加到列表中( SchoolStudentCollegeStudent等)。 現在開發人員可以使用Student接口創建匿名類,實現一些錯誤的payFees方法並將該對象添加到studentlist。 這個匿名學生無效,它會分散業務邏輯。

那么我們如何保護開發人員不要創建匿名的Student接口類。

我能想到的一種方法是(假設Student接口的所有有效實現都在同一個包中)來定義一個包私有附加接口(讓我們稱之為ValidStudent ),除了實現Student之外,有效的實現還會實現。 該包私有接口不必包含任何方法。

然后,您可以使用一些代碼來驗證添加到ListStudent實例 - 驗證代碼將檢查這些實例是否也實現了ValidStudent接口。 Student任何自定義實現都不會通過該驗證。

package x;
public interface Student
{
    ...
}

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

package x;
public class SchoolStudent implements Student, ValidStudent
{

}

並且驗證的一個例子(驗證可以由包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