代码已上传至Github,有兴趣的同学可以下载来看看:https://github.com/ylw-github/Java-DesignMode
外观模式(Facade Pattern)门面模式,隐藏系统的复杂性,并向客户端提供了一个客户端可以访问系统的接口。这种类型的设计模式属于结构型模式,它向现有的系统添加一个接口,来隐藏系统的复杂性。
这种模式涉及到一个单一的类,该类提供了客户端请求的简化方法和对现有系统类方法的委托调用。
下面来举个例子,用户注册完之后,需要调用阿里短信接口、邮件接口、微信推送接口。
1.阿里微信发送消息接口
public interface IAliService {
void sendSMS(String msg);
}
public class AliService implements IAliService {
@Override
public void sendSMS(String msg) {
System.out.println("支付宝发送消息 -> "+msg);
}
}
2.微信发送消息接口
public interface IWeixinService {
void sendSMS(String msg);
}
public class WeixinService implements IWeixinService {
@Override
public void sendSMS(String msg) {
System.out.println("微信发送信息-> " + msg);
}
}
3.foxmail发送消息接口
public interface IFoxmailService {
void sendSMS(String msg);
}
public class FoxmailService implements IFoxmailService {
@Override
public void sendSMS(String msg) {
System.out.println("foxmail发送消息 -> " + msg);
}
}
4.门面类
public class Computer {
private IAliService aliService;
private IWeixinService weixinService;
private IFoxmailService foxmailService;
public Computer(){
aliService = new AliService();
weixinService = new WeixinService();
foxmailService = new FoxmailService();
}
public void sendGroupMsg(String msg){
aliService.sendSMS(msg);
weixinService.sendSMS(msg);
foxmailService.sendSMS(msg);
}
}
5.测试
public class Client {
public static void main(String[] args) {
Computer computer = new Computer();
computer.sendGroupMsg("明天不用加班...");
}
}