设计模式之外观模式

定义:将细粒度的对象包装成粗粒度的对象,应用程序通过访问这个外观对象,来完成细粒度对象的调用,我们通过外观的包装,使应用程序只能看到外观对象,而不会看到具体的细节对象,这样无疑会降低应用程序的复杂度,并且提高了程序的可维护性。

优点:1、减少系统相互依赖。 2、提高灵活性。 3、提高了安全性。

缺点:不符合开闭原则,如果要改东西很麻烦,继承重写都不合适。

结构图:通过外观对象来组织细粒度的服务的调用,外观对象提供给外部应用程序可以使用的服务,而具体的调用细粒度的过程则被外观对象给封装起来,当然这个过程就是封装变化的部分,而将变化的部分与应用程序进行隔离,无疑对程序的易用性和可维护性都是很大的提高。

应用:一下案例通过客户端通过外观对象调用不同的形状对象的服务,减少了客户端和应用端的交互,简化的步骤,将外观对象做成单例类,可以在使用对象时减少内存的分配。
1.创建一个接口。

public interface Shape { void draw();}
2.创建接口的实现类(对象):

1
2
3
4
5
6
7
8
9
10
11
12
13
14
public class Rectangle : Shape
{
public void Draw() { }
}

public class Square : Shape
{
public void Draw(){ }
}

public class Circle : Shape
{
public void Draw() { }
}

3.创建外观对象:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
public class ShapeMaker {
private Shape circle;
private Shape rectangle;
private Shape square;

public ShapeMaker() {
circle = new Circle();
rectangle = new Rectangle();
square = new Square();
}

public void drawCircle(){
circle.draw();
}
public void drawRectangle(){
rectangle.draw();
}
public void drawSquare(){
square.draw();
}
}

4.创建客户端,调用外观对象:

1
2
3
4
5
6
7
8
9
public class Client {
public static void main(String[] args) {
ShapeMaker shapeMaker = new ShapeMaker();

shapeMaker.drawCircle();
shapeMaker.drawRectangle();
shapeMaker.drawSquare();
}
}