外观模式
1、外观模式(Facade Pattern)隐藏系统的复杂性,并向客户端提供了一个客户端可以访问系统的接口。这种类型的设计模式属于结构型模式,它向现有的系统添加一个接口,来隐藏系统的复杂性。这种模式涉及到一个单一的类,该类提供了客户端请求的简化方法和对现有系统类方法的委托调用。
2、例子
这个例子可能大家在日常开发中都会用到,只不过在不了解外观模式的情况下,也不知道。比如一些提供给web或者client的接口的开发就是外观模式的应用。1、JAVA 的三层开发模式。
3、外观模式的优缺点
优点:
1、减少系统相互依赖。 2、提高灵活性。 3、提高了安全性。
缺点:
不符合开闭原则,如果要改东西很麻烦,继承重写都不合适。
4、代码
public class EntryptTest {
public static void main(String[] args) throws Exception {
ShapeMaker shapeManage = new ShapeMaker();
shapeManage.drawCircle();
shapeManage.drawRectangle();
shapeManage.drawSquare();
}
}
//创建一个接口
interface Shape {
void draw();
}
//创建实现接口的具体类
class Rectangle implements Shape {
@Override
public void draw() {
System.out.println("this is Rectangle draw()");
}
}
class Circle implements Shape {
@Override
public void draw() {
System.out.println("this is Circle draw()");
}
}
class Square implements Shape {
@Override
public void draw() {
System.out.println("this is Square draw()");
}
}
//创建一个外观类,为外部提供接口
class ShapeMaker {
private Rectangle rectangle;
private Circle circle;
private Square square;
public ShapeMaker() {
this.rectangle = new Rectangle();
this.circle = new Circle();
this.square = new Square();
}
public void drawRectangle() {
rectangle.draw();
}
public void drawSquare() {
square.draw();
}
public void drawCircle() {
circle.draw();
}
}
运行结果:
this is Circle draw()
this is Rectangle draw()
this is Square draw()
分析:
我们将创建一个 Shape 接口和实现了 Shape 接口的实体类。下一步是定义一个外观类 ShapeMaker。
ShapeMaker 类使用实体类来代表用户对这些类的调用。main方法中我们的演示类使用 ShapeMaker 类来显示结果。
这只是一个最简单的模型,正常开发中都是Manager或者ManagerImpl,然后上面还会再有一层Facade和FacadeImpl,使得client或web调用Facade接口。