设计模式(二)-- 外观模式(Facade)

时间:2024-01-04 08:14:38

设计模式(二)

外观模式(Facade)

为了解决子系统外部的客户端在使用子系统的时候,既能简单地使用这些子系统内部的模块功能,而又不用客户端去与子系统内部的多个模块交互的问题。

为子系统中的一组接口提供一个一致的界面,外观模式定义了一个高层接口,这个接口使得这一子系统更加容易使用。

外观模式就是通过引入一个外观类,在这个类里面定义客户端想要的简单的方法,然后在这些方法的实现里面,由外观类再去分别调用内部的多个模块来实现功能,从而让客户端变得简单。这样一来,客户端就只需要和外观类交互就可以了。

package Facade;

public classConfigModel {

private boolean needGenPresentation = true;

private boolean needGenBusiness = true;

private boolean needGenDAO = true;

public boolean isNeedGenPresentation(){

return needGenPresentation;

}

public boolean isNeedGenBusiness(){

return needGenBusiness;

}

public boolean isNeedGenDAO(){

return needGenDAO;

}

public void setNeedGenPresentation(boolean needGenPresentation){

this.needGenPresentation=needGenPresentation;

}

public void setNeedGenBusiness(boolean needGenBusiness){

this.needGenBusiness=needGenBusiness;

}

public void setNeedGenDAO(boolean needGenDAO){

this.needGenDAO=needGenDAO;

}

}

package Facade;

public classConfigManager {

private static ConfigManager manager = null;

private static ConfigModel cm = null;

private ConfigManager(){

//

}

public static ConfigManager getInstance(){

if(manager==null){

manager = new ConfigManager();

cm new ConfigModel();

}

return manager;

}

public ConfigModel getConfigDate(){

return cm;

}

}

package Facade;

public classPresentation {

public void generate(){

ConfigModel cm = ConfigManager.getInstance().getConfigDate();

if(cm.isNeedGenPresentation()){

System.out.println("Generate Presentation Layer");

}

}

}

package Facade;

public classBusiness {

public void generate(){

ConfigModel cm = ConfigManager.getInstance().getConfigDate();

if(cm.isNeedGenBusiness()){

System.out.println("Generate Business Layer");

}

}

}

package Facade;

public classDAO {

public void generate(){

ConfigModel cm = ConfigManager.getInstance().getConfigDate();

if(cm.isNeedGenDAO()){

System.out.println("Generate DAO Layer");

}

}

}

package Facade;

public classFacade {

publicvoidgenerate(){

new Presentation().generate();

new Business().generate();

new DAO().generate();

}

}

package Facade;

public classClient {

publicstaticvoidmain(String[] args){

new Facade().generate();

}

}

Output:

Generate Presentation Layer

Generate Business Layer

Generate DAO Layer