设计模式-门面模式

179 阅读2分钟

门面模式的定义

门面模式也称为外观模式,要求一个子系统的外部和内部之间的通信必须通过一个统一的对象进行,门面模式提供一个高层次的接口,使得子系统更易于使用

门面模式注重统一的对象,也就是提供一个访问子系统的接口,除了这个接口不允许有任何访问子系统的行为发生

门面模式案例

/**
 * 写信过程接口
 */
public interface ILetterProcess {
    //首先写信的内容
    void writeContext(String context);

    //其次写信封
    void fillEnvelope(String address);

    //把信放到信封中
    void letterIntoEnvelope();

    //然后邮递
    void sendLetter();
}
/**
 * @author cuckooYang
 * @create 2020-08-06 15:16
 * @description 写信过程实现类
 **/

public class LetterProcessImpl implements ILetterProcess {
    @Override
    public void writeContext(String context) {
        System.out.println("填写信的内容..."+context);
    }

    @Override
    public void fillEnvelope(String address) {
        System.out.println("填写收件人地址及姓名..."+address);
    }

    @Override
    public void letterIntoEnvelope() {
        System.out.println("把信放到信封中...");
    }

    @Override
    public void sendLetter() {
        System.out.println("邮递信件...");
    }
}

package structuralDesgin.facadePattern;

/**
 * @author cuckooYang
 * @create 2020-08-06 15:18
 * @description 邮局类
 **/

public class ModenPostOffice {
    private ILetterProcess iLetterProcess = new LetterProcessImpl();

    //写信,封装,投递,一体化
    public void sendLetter(String context ,String address){
        //帮你写信
        iLetterProcess.writeContext(context);

        //写好信封
        iLetterProcess.fillEnvelope(address);

        //把信放入到信封中
        iLetterProcess.letterIntoEnvelope();

        //邮递信件
        iLetterProcess.sendLetter();
    }

}

/**
 * @author cuckooYang
 * @create 2020-08-06 15:21
 * @description
 **/

public class Main {
    public static void main(String[] args) {
        ModenPostOffice modenPostOffice = new ModenPostOffice();

        String address = "Happy Road No. 666, God Province, Heaven";

        String context = "Hello, It's me, do you know who I am? I'm your old lover. I'd like to....";
        modenPostOffice.sendLetter(context,address);
    }
}

门面模式的优点

  • 减少系统的相互依赖

    如果我们不使用门面模式,外部访问直接深入到子系统内部,相互之间是一种强耦合关系

  • 提高了灵活性

    依赖减少了,灵活性自然提高了,不管子系统如何变化,只要不影响到门面对象,就没有影响

  • 提高了安全性

    子系统无论开发了什么功能,如果没有在门面模式开通,就访问不到

门面模式的缺点

门面模式最大的缺点是不符合开闭原则

门面模式的使用场景

  • 为一个复杂的模块或者子系统提供一个供外界访问的接口
  • 子系统相对独立