1.什么是外观模式
外观模式(Facade Pattern)门面模式,隐藏系统的复杂性,并向客户端提供了一个客户端可以访问系统的接口。这种类型的设计模式属于结构型模式,它向现有的系统添加一个接口,来隐藏系统的复杂性。
这种模式涉及到一个单一的类,该类提供了客户端请求的简化方法和对现有系统类方法的委托调用。
2.外观模式代码示例
用户注册完之后,需要调用阿里短信接口、邮件接口、微信推送接口。
/**
* @ClassName AliSmsService
* @Author ywj
* @Describe
* @Date 2020/5/25 16:08
*/
public interface AliSmsService {
void sendAliSms();
}
public interface EamilSmsService {
void sendSms();
}
public interface WeiXinSmsService {
void sendWxMsg();
}
实现类
public class AliSmsServiceImpl implements AliSmsService {
@Override
public void sendAliSms() {
System.out.println("发送阿里云消息提示!!!");
}
}
public class EamilSmsServiceImpl implements EamilSmsService {
@Override
public void sendSms() {
System.out.println("实现发送邮件消息功能!!!");
}
}
public class WeiXinSmsServiceImpl implements WeiXinSmsService {
@Override
public void sendWxMsg() {
System.out.println("微信公众号消息推送!!!");
}
}
门面类
package creationtype.facade;
/**
* @ClassName ComputerController
* @Author ywj
* @Describe
* @Date 2020/5/25 16:10
*/
public class ComputerController {
AliSmsService aliSmsService;
EamilSmsService eamilSmsService;
WeiXinSmsService weiXinSmsService;
public ComputerController() {
aliSmsService = new AliSmsServiceImpl();
eamilSmsService = new EamilSmsServiceImpl();
weiXinSmsService = new WeiXinSmsServiceImpl();
}
public void sendMsg() {
aliSmsService.sendAliSms();
eamilSmsService.sendSms();
weiXinSmsService.sendWxMsg();
}
}
模拟客户端调用
package creationtype.facade;
/**
* @ClassName client
* @Author ywj
* @Describe 外观模式
* @Date 2020/5/21 11:38
*/
public class client {
public static void main(String[] args) {
ComputerController controller = new ComputerController();
controller.sendMsg();
}
}
结果
3.外观模式总结
1.优点
- 减少了系统的相互依赖
- 提高了灵活性。不管系统内部如何变化,只要不影响到外观对象,任你自由活动
- 提高了安全性。想让你访问子系统的哪些业务就开通哪些逻辑,不在外观上开通的方法,你就访问不到
2.缺点
- 不符合开不原则,修改很麻烦
3.使用场景
- 为一个复杂的模块或子系统提供一个外界访问的接口
- 子系统相对独立,外界对子系统的访问只要黑箱操作即可
- 预防低水平人员带来的风险扩散
其实这个外观模式,我感觉就像是我们平时使用的MVC三层架构,层层架构中降低耦合,方便使用,不方便的也是我写个新接口就得三层一起写