设计模式之外观模式(Facade)

版权声明:本文为博主原创文章,转载请注明出处 https://blog.csdn.net/qq_23934475/article/details/82999161

设计模式之外观模式(Facade)

场景

病人去医院看病,首先病人必须先挂号,然后门诊。如果医生要求化验,病人必须首先划价,然后缴费,才可以到化验部门做化验。化验后再回到门诊室。
解决这种不便的方法便是引进外观模式,医院可以设置一个接待员的位置,由接待员负责代为挂号、划价、缴费、取药等。这个接待员就是外观模式的体现,病人只接触接待员,由接待员与各个部门打交道。

这篇文章对外观模式讲的不错
https://www.jianshu.com/p/b9dd384d14a8

门诊

public class Outpatient {

    //耳鼻喉科
    public void ent(){
        System.out.println("outpatient ent");
    }

    //皮肤科
    public void dermatology(){
        System.out.println("outpatient dermatology");
    }
}

挂号

public class Registration {
    //耳鼻喉科
    public void ent(){
        System.out.println("Registration ent");
    }

    //皮肤科
    public void dermatology(){
        System.out.println("Registration dermatology");
    }
}

缴费

public class Pay {

    public void payFees(){
        System.out.println("pay the fees.");
    }
}

取药

public class Medicine {
    public void getMedicine(){
        System.out.println("get the medicine.");
    }
}

接待员进行封装

public class Facade {

    private Outpatient outpatient;

    private Registration registration;

    private Pay pay;

    private Medicine medicine;

    public Facade(){
        outpatient = new Outpatient();
        registration = new Registration();
        pay = new Pay();
        medicine = new Medicine();
    }

    public void ent(){
        registration.ent();
        outpatient.ent();
        pay.payFees();
        medicine.getMedicine();
    }

    public void dermatology(){
        registration.dermatology();
        outpatient.dermatology();;
        pay.payFees();
        medicine.getMedicine();
    }
}

测试

public class APP {
    @Test
    public void facadeTest(){
        Facade facade = new Facade();

        facade.ent();

        System.out.println("===========");
        facade.dermatology();
    }

}

类图
在这里插入图片描述

使用外观模式还有一个附带的好处,就是能够有选择性地暴露方法
外观模式的目的不是给予子系统添加新的功能接口,而是为了让外部减少与子系统内多个模块的交互,松散耦合,从而让外部能够更简单地使用子系统。

扫描二维码关注公众号,回复: 3614521 查看本文章

外观模式的本质是:封装交互,简化调用。

猜你喜欢

转载自blog.csdn.net/qq_23934475/article/details/82999161