本文共 1052 字,大约阅读时间需要 3 分钟。
外观模式:隐藏系统的复杂性,向客户端提供了一个客户端可以访问系统的接口、减少客户端对系统的复杂性。
代码示例: 1.创建接口Shapepublic interface Shape { void draw();}
2.创建实现类Rectangle、Circle、Square类
/** * 矩形 */public class Rectangle implements Shape{ @Override public void draw() { System.out.println("画矩形"); }}
/** * 正方形 */public class Square implements Shape{ @Override public void draw() { System.out.println("画正方形"); }}
/** * 正方形 */public class Square implements Shape{ @Override public void draw() { System.out.println("画正方形"); }}
2.创建ShapeMaker类,供客户端使用
public class ShapeMaker { public void draw() { new Rectangle().draw(); new Circle().draw(); new Square().draw(); }}
3.测试
public class TestShapeMaker { public static void main(String[] args) { ShapeMaker shapeMaker = new ShapeMaker(); shapeMaker.draw(); }}根据上面的可知,客户端需要画一个正方形、长方形、圆形,如果客户端自己去创建这些对象,然后调用,这样对于客户端来说就非常复杂,而通过外观模式,我们只需要调用ShapeMaker的方法即可,具体的画这些图形的过程,我们不需要关心,大大降低了客户端与系统之间访问的复杂性。优点: 1、减少系统相互依赖。 2、提高灵活性。 3、提高了安全性。
缺点:不符合开闭原则,如果要改东西很麻烦,继承重写都不合适。
转载地址:http://sswmf.baihongyu.com/