设计模式-结构型模式之外观模式

120 阅读2分钟

结构型模式-外观模式

image.png

外观模式

外观模式(Facade Pattern)也被叫做门面模式,外观模式提供一个高层次的接口,使得子系统更易于使用,就相当于提供了一个门面。

外观模式算是一个比较常用的设计模式了。

以常见的开发为例:第三方调用接口,我们有三个子系统分别承担不同的功能,我们可以提供一个门面来让第三方调用,而无需让第三方直接调用三个子系统来实现功能。

image.png

举个例子:假设现在要邮寄一封信,需要的步骤1、写信,2、买信封,3、装进信封,4、寄信,如果每次寄信都需要这四步,就会很繁琐。这个时候就有了邮局,你只需要把写好的信交给我,然后邮局会帮你把剩下的事情做完。

image.png

写信的抽象接口

public interface ILetterProcess {  
    //写信  
    void write(String context);  
    //买信封  
    void buyEnvelope();  
    //把信装入信封  
    void letterIntoEnvelope();  
    //寄信  
    void sendLetter();  
}

写信的抽象实现

public class LetterProcessImpl implements ILetterProcess{  
    @Override  
    public void write(String context) {  
        System.out.println("写信="+context);  
    }  

    @Override  
    public void buyEnvelope() {  
        System.out.println("买信封.....");  
    }  

    @Override  
    public void letterIntoEnvelope() {  
        System.out.println("把信装入信封......");  
    }  

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

邮局

public class PostOfficeImpl{  
  
    private LetterProcessImpl letterProcess = new LetterProcessImpl();  

    public void sendLetter(String context){  
        letterProcess.write(context);  
        letterProcess.buyEnvelope();  
        letterProcess.letterIntoEnvelope();  
        letterProcess.sendLetter();  
    }  
}

测试

public static void main(String[] args) {  
    PostOfficeImpl postOffice = new PostOfficeImpl();  
    postOffice.sendLetter("这就是信的内容");  
}

贴一个类图结构:

image.png


外观模式的优点:

  • 减少系统的相互依赖
  • 提高系统安全性,减少外部系统对内部各个子系统的访问

外观模式的缺点:

  • 不符合开闭原则,一旦门面类有问题,比如缺少了某个参数,这个时候就需要修改门面类而且还可能造成第三方代码的改动。