设计模式外观设计模式
外观设计模式
定义:为子系统提供一个一致的界面,定义一个高层接口,使得子系统更容易使用
外观模式(Facade Pattern)是经常使用的设计模式
例子
以大话设计模式为例,散户自己操盘,也可以通过基金经理来操盘,通过基金经理操盘就体现了外观模式
股票类
package com.learn.java.javabase.designpattern.facad;
import lombok.extern.slf4j.Slf4j;
@Slf4j
public class Socket01 {
public void sell(){
log.info("sell socket01");
}
public void buy(){
log.info("buy socket02");
}
}
package com.learn.java.javabase.designpattern.facad;
import lombok.extern.slf4j.Slf4j;
@Slf4j
public class Socket02 {
public void sell(){
log.info("sell socket02");
}
public void buy(){
log.info("buy socket02");
}
}
package com.learn.java.javabase.designpattern.facad;
import lombok.extern.slf4j.Slf4j;
@Slf4j
public class Socket03 {
public void sell(){
log.info("sell socket03");
}
public void buy(){
log.info("buy socket03");
}
}
国债类
package com.learn.java.javabase.designpattern.facad;
import lombok.extern.slf4j.Slf4j;
@Slf4j
public class Found {
Socket01 socket01 = new Socket01();
Socket02 socket02 = new Socket02();
Socket03 socket03 = new Socket03();
NationalDebt nationalDebt = new NationalDebt();
public void methodA(){
log.info("found methodA");
socket01.sell();
socket02.buy();
}
public void methodB(){
log.info("found methodB");
socket03.buy();
nationalDebt.buy();
}
}
基金类
package com.learn.java.javabase.designpattern.facad;
public class Found {
Socket01 socket01 = new Socket01();
Socket02 socket02 = new Socket02();
Socket03 socket03 = new Socket03();
NationalDebt nationalDebt = new NationalDebt();
public void methodA(){
socket01.sell();
socket02.buy();
}
public void methodB(){
socket03.buy();
nationalDebt.buy();
}
}
测试类
package com.learn.java.javabase.designpattern.facad;
public class TestFacade {
public static void main(String[] args) {
Found found =new Found();
found.methodA();
found.methodB();
}
}
运行结果
22:38:03.852 [main] INFO com.learn.java.javabase.designpattern.facad.Found - found methodA
22:38:03.858 [main] INFO com.learn.java.javabase.designpattern.facad.Socket01 - sell socket01
22:38:03.858 [main] INFO com.learn.java.javabase.designpattern.facad.Socket02 - buy socket02
22:38:03.858 [main] INFO com.learn.java.javabase.designpattern.facad.Found - found methodB
22:38:03.858 [main] INFO com.learn.java.javabase.designpattern.facad.Socket03 - buy socket03
22:38:03.858 [main] INFO com.learn.java.javabase.designpattern.facad.NationalDebt - buy national debt
例子说明
基金的行为是对外暴露的,即对外提供了一个接口,内部的行为是不知道了,调用方只需要知道外在的接口就可以了。
具体股票或者国债的操作已经通过投资基金类完成了。很好的体现了迪米特法则
**迪米特法则(最少知识法则) **
两个类不需要直接通信,就不发生相互作用,如果需要通信,一个类需要调用另外一个
类的方法,通过第三个类来转发这个调用