本文源码:GitHub·点这里 || GitEE·点这里
一、生活场景
1、场景描述
2、代码图解
3、代码实现
/**
* 外观模式描述饭店就餐流程
*/
public class C01_InScene {
public static void main(String[] args) {
EatAppFacade eatAppFacade = new EatAppFacade () ;
eatAppFacade.dining();
}
}
// 预定
class Booking {
private static Booking booking = new Booking() ;
public static Booking getInstance (){
return booking ;
}
public void bookPlace (){
System.out.println("位置预定...");
}
}
// 点餐
class TakeOrder {
private static TakeOrder takeOrder = new TakeOrder ();
public static TakeOrder getInstance (){
return takeOrder ;
}
public void orderDishes (){
System.out.println("点餐...");
}
}
// 付款
class Payment {
private static Payment payment = new Payment () ;
public static Payment getInstance (){
return payment ;
}
public void payMoney (){
System.out.println("结账...");
}
}
// 点餐APP
class EatAppFacade {
private Booking booking ;
private TakeOrder takeOrder ;
private Payment payment ;
public EatAppFacade (){
this.booking = Booking.getInstance() ;
this.takeOrder = TakeOrder.getInstance() ;
this.payment = Payment.getInstance() ;
}
// 就餐流程
public void dining (){
booking.bookPlace();
takeOrder.orderDishes();
payment.payMoney();
}
}
二、外观设计模式
1、基本简介
2、模式图解
3、核心角色
- 外观角色
- 子模块角色
- 客户端角色
4、源代码实现
public class C02_Facade {
public static void main(String[] args) {
Facade facade = new Facade();
facade.clientNeed1();
facade.clientNeed2();
}
}
class ModuleA {
public void testA (){
System.out.println("ModuleA.testA()");
}
}
class ModuleB {
public void testB (){
System.out.println("ModuleB.testB()");
}
}
class ModuleC {
public void testC (){
System.out.println("ModuleC.testC()");
}
}
class Facade {
/**
* 客户需求1
*/
public void clientNeed1 (){
ModuleA moduleA = new ModuleA();
moduleA.testA();
ModuleB moduleB = new ModuleB();
moduleB.testB();
}
/**
* 客户需求1
*/
public void clientNeed2 (){
ModuleB moduleB = new ModuleB();
moduleB.testB();
ModuleC moduleC = new ModuleC();
moduleC.testC();
}
}
三、Mybatis应用场景
1、使用场景
- org.apache.ibatis.session.Configuration
- org.apache.ibatis.reflection.MetaObject
Configuration 创建 MetaObject 的时候。
2、Configuration源码
public class Configuration {
protected ObjectFactory objectFactory;
protected ObjectWrapperFactory objectWrapperFactory;
public Configuration() {
this.objectFactory = new DefaultObjectFactory();
this.objectWrapperFactory = new DefaultObjectWrapperFactory();
}
public MetaObject newMetaObject(Object object) {
return MetaObject.forObject(object, this.objectFactory, this.objectWrapperFactory);
}
// ... 省去其他源码
}
3、MetaObject 源码
public static MetaObject forObject(Object object,
ObjectFactory objectFactory,
ObjectWrapperFactory objectWrapperFactory) {
return object == null ?
SystemMetaObject.NULL_META_OBJECT :
new MetaObject(object, objectFactory, objectWrapperFactory);
}
四、优缺点总结
五、源代码地址
GitHub·地址
https://github.com/cicadasmile/model-arithmetic-parent
GitEE·地址
https://gitee.com/cicadasmile/model-arithmetic-parent