外观模式属于设计模式里的结构型模式的一种,核心思想是隐藏系统的复杂性,并向客户端 提供了可以访问的接口。
个人认为外观模式是其他设计模式的基础,在许多模式里都有体现。较易掌握。
思路:
- 设计一个接口和分别实现接口的类(系统类)
- 设计一个类(实现类),类的数据成员是系统类对象,private控制权限,封装
- 类的的方法分别调用数据成员对象的方法
- 最后public类main方法调用展现
设计:
- 一个接口Shape,和实现接口类Circle、Rectangle、Square,各类重写接口里的抽象方法
- 一个实现类,ShapeMaker把接口实现类的各个对象封装,方法调用
代码:
interface Shape{
void draw();
}
class Rectangle implements Shape{
public void draw() {
System.out.println("Rectangle:draw()");
}
}
class Square implements Shape{
public void draw() {
System.out.println("Square:draw()");
}
}
class Circle implements Shape{
public void draw() {
System.out.println("Circle:draw()");
}
}
class ShapeMaker{
private Shape circle;
private Shape rectangle;
private Shape square; //封装系统内部复杂性,提供外部接口调用
ShapeMaker(){
circle=new Circle();
rectangle=new Rectangle();
square=new Square();
}
public void drawCircle(){
circle.draw();
}
public void drawRecrangle(){
rectangle.draw();
}
public void drawSquare(){
square.draw();
}
}
public class FacadePatternDemo {
public static void main(String[] args) {
ShapeMaker shapeMaker=new ShapeMaker();
shapeMaker.drawCircle();
shapeMaker.drawRecrangle();
shapeMaker.drawSquare();
}
}
输出:
Circle:draw()
Rectangle:draw()
Square:draw()
总结:
- 简单易用
- 是面向接口编程和组合编程的思想体现
- 但是改变麻烦