簡體   English   中英

如何使用內部類正確實現Java接口?

[英]How do I properly implement my Java interface with inner class?

我有一段代碼將事件寫入日志文件:

Date rightNow = new Date();
File logfile = new File(Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOCUMENTS), ("MyLogfile" + fileSDF.format(rightNow) + ".txt"));
FileOutputStream fos;
boolean documents_directory_exists = logfile.getParentFile().exists();
boolean documents_directory_created = true;
if(!documents_directory_exists) documents_directory_created = logfile.getParentFile().mkdirs();
if(documents_directory_created){
    try {
        fos = new FileOutputStream(logfile, true);
        fos.write(new LogEntry(timestampSDF.format(rightNow), boolean01, someInt, boolean02).toString().getBytes());
        fos.close();
    } catch (IOException ioe) {
        Log.e(SomeClass.class.getName(), String.format(Locale.US, "%s %s", Constants.DEFAULT_FILE_ERROR_MESSAGE, ioe.getMessage()));
    }
} else {
        Log.e(SomeClass.class.getName(), String.format(Locale.US, "%s %s", Constants.DEFAULT_FILE_ERROR_MESSAGE, "Cannot create the necessary directories."));
}

我在多個地方都有此代碼,所以我想將其粘貼在接口中,以便使代碼更整潔。 所以我創建了這個接口:

public interface LogWriter {
    void writeLog(LogEntry logEntry);
}

其中LogEntry是:

public class LogEntry{
    private String timestamp;
    private boolean booean01;
    private int someInt;
    private boolean boolean02;

    public LogEntry(timestamp, boolean01, someInt, boolean02){
        this.timestamp = timestamp;
        this.boolean01= boolean01;
        this.someInt= someInt;
        this.boolean02= boolean02;
    }

    // Getters and Setters
}

我想保持代碼的整潔,所以我想在接口中執行所有文件I / O,所以我創建了一個內部類:

public interface LogWriter {
    void writeLog(LogEntry logEntry);

    class WriteMeToTheLog {
        LogEntry logEntry;

        private static final SimpleDateFormat fileSDF = new SimpleDateFormat(Constants.ACCESS_LOGFILE_NAME_FORMAT);

        public WriteMeToTheLog(LogEntry logEntry) {
            this.logEntry = logEntry;
        }

        public void write(){
             Date rightNow = new Date();
             File logfile = new File(Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOCUMENTS), ("MyLogfile" + fileSDF.format(rightNow) + ".txt"));
             FileOutputStream fos;
             boolean documents_directory_exists = logfile.getParentFile().exists();
             boolean documents_directory_created = true;
             if(!documents_directory_exists) documents_directory_created = logfile.getParentFile().mkdirs();
             if(documents_directory_created){
                 try {
                     fos = new FileOutputStream(logfile, true);
                     fos.write(new LogEntry(timestampSDF.format(rightNow), boolean01, someInt, boolean02).toString().getBytes());
                     fos.close();
                 } catch (IOException ioe) {
                     Log.e(SomeClass.class.getName(), String.format(Locale.US, "%s %s", Constants.DEFAULT_FILE_ERROR_MESSAGE, ioe.getMessage()));
                }
            } else {
                Log.e(SomeClass.class.getName(), String.format(Locale.US, "%s %s", Constants.DEFAULT_FILE_ERROR_MESSAGE, "Cannot create the necessary directories."));
            }
        }
    }
}

這是我收到失落。

在具有原始代碼塊的一個類中,我實現了新接口:

public class OneOfMyClasses extends BaseClass implements LogWriter {
    public myMethod(){
        // This is where I had the original block of code
        // WHAT DO I DO HERE NOW???
    }

    @Override
    public void writeLog(){
        Date rightNow = new Date();
        writeMeToTheLog(new LogEntry(timestampSDF.format(rightNow), boolean01, someInt, boolean02).toString().getBytes());
        writeMeToTheLog.write();
    }
}

如何使用這項新功能?

我想保持代碼的整潔,所以我想在接口中執行所有文件I / O,因此我創建了一個內部類

在接口中聲明一個類不是“干凈的”。
此外,這不是內部類,而是靜態類,因為該類在接口中聲明。
所有這些都是相對直觀的。 該類是一個實現,而接口是一個API。 API聲明實現結構聽起來並不好。

關於您的問題,我認為WriteMeToTheLog (包含您提取的日志記錄邏輯)還必須實現LogWriter因為它看起來像LogWriter實現。
客戶端類應該具有對WriteMeToTheLog的依賴關系,可能是在構造函數中設置的字段,盡管它仍然可以實現LogWritter如果有意義)。

那會給:

class WriteMeToTheLog implements LogWriter { ...}

和:

public class OneOfMyClasses extends BaseClass implements LogWriter {
    private LogWriter logWriter;

    public OneOfMyClasses (LogWriter logWriter){
       this.logWriter = logWriter;
    }

    @Override
    public void writeLog(){
        Date rightNow = new Date();       
        logWriter.write();
    }
}

現在,您可以通過設置依賴關系來實例化客戶端類:

OneOfMyClasses o = new OneOfMyClasses(new WriteMeToTheLog(new LogEntry(timestampSDF.format(rightNow), boolean01, someInt, boolean02).toString().getBytes());

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM