設計模式:日誌記錄器——工廠方法模式

qq_41373594發表於2018-03-08

例項類圖:

                                                                     

例項程式碼:

package logbag;

 

public interface Log {

 public void writeLog();

}

package logbag;

 

public interface LogFactory {

     public Log createLog();

}

public class DatabaseLog implements Log{

       publicvoid writeLog(){

        System.out.println("寫資料日誌");

       }

 

}

package logbag;

 

public class DatabaseLogFactory implementsLogFactory{

       publicLog createLog(){

              System.out.println("建立資料檔案");

              returnnew DatabaseLog();

       }

 

}

package logbag;

 

public class FileLog implements Log {

       publicvoid writeLog(){

       System.out.println("寫日誌");

       }

}

package logbag;

 

public class FileLogFactory implementsLogFactory {

@Override

 public Log createLog(){

        System.out.println("建立新的日誌檔案");

        return new FileLog();

 }

}

 

public class LogTest {
    public static void main(String[]args) {
        try{
            Log log;
            LogFactory factory;
            factory = newFileLogFactory();
            log=factory.createLog();
            log.writeLog();
            factory = newDatabaseLogFactory();
            log=factory.createLog();
            log.writeLog();

        }catch(Exception e)
        {
            System.out.println(e.getMessage());
        }
    }
}

 

相關文章