一.外观设计模式所解决的问题
外观设计模式为子系统中的一组接口提供统一的接口,这种统一的接口屏蔽了直接调用子系统时的逻辑关系,使得调用子系统时更容易。
二.外观设计模式用例
假如一个应用中有两个接口MysqLHelper.class和OracleHelper.class,两个接口功能分别是连接MysqL和oracle数据库,然后生成HTML报表或者PDF报表,代码说明如下:
MysqLHelper.class和OracleHelper.class
import java.sql.Connection; class MysqLHelper { public static Connection getMysqLDBConnection(){ //get MysqL DB connection using connection parameters return null; } public void generateMysqLPDFReport(String tableName,Connection con){ //get data from table and generate pdf report } public void generateMysqLHTMLReport(String tableName,Connection con){ //get data from table and generate pdf report } } class OracleHelper { public static Connection getOracleDBConnection(){ //get Oracle DB connection using connection parameters return null; } public void generateOraclePDFReport(String tableName,Connection con){ //get data from table and generate pdf report } public void generateOracleHTMLReport(String tableName,Connection con){ //get data from table and generate pdf report } }
外观类HelperFacade.class
import java.sql.Connection
class HelperFacade{ public static void generateReport(DatabaseType dbType,ReportType reportType,String tableName){ Connection con=null; switch (dbType){ case MysqL: con=MysqLHelper.getMysqLDBConnection(); MysqLHelper MysqLHelper=new MysqLHelper(); switch (reportType){ case HTML: MysqLHelper.generateMysqLHTMLReport(tableName,con); break; case PDF: MysqLHelper.generateMysqLPDFReport(tableName,con); break; } break; case ORACLE: con=MysqLHelper.getMysqLDBConnection(); OracleHelper oracleHelper=new OracleHelper(); switch (reportType){ case HTML: oracleHelper.generateOracleHTMLReport(tableName,con); break; case PDF: oracleHelper.generateOraclePDFReport(tableName,con); break; } } } public static enum DatabaseType{ MysqL,ORACLE } public static enum ReportType{ HTML,PDF } }
import java.sql.Connection; import com.journaldev.design.facade.HelperFacade; import com.journaldev.design.facade.MysqLHelper; import com.journaldev.design.facade.OracleHelper; public class FacadePatternTest { public static void main(String[] args) { String tableName="Employee"; //generating MysqL HTML report and Oracle PDF report without using Facade Connection con = MysqLHelper.getMysqLDBConnection(); MysqLHelper MysqLHelper = new MysqLHelper(); MysqLHelper.generateMysqLHTMLReport(tableName,con); Connection con1 = OracleHelper.getOracleDBConnection(); OracleHelper oracleHelper = new OracleHelper(); oracleHelper.generateOraclePDFReport(tableName,con1); //generating MysqL HTML report and Oracle PDF report using Facade HelperFacade.generateReport(HelperFacade.DBTypes.MysqL,HelperFacade.ReportTypes.HTML,tableName); HelperFacade.generateReport(HelperFacade.DBTypes.ORACLE,HelperFacade.ReportTypes.PDF,tableName); } }
三.外观设计模式使用场景
1.外观设计模式可以运用在任何开发阶段,通常用在接口数量越来越多、系统变得复杂的时候。
2.子接口不应该有外观类的引用。