外观模式(Facade Pattern)

外观模式:对一个集合接口提供统一的接口并将其作为子系统,门面定义了更高一级的接口,它能够使子系统更容易使用。像spring一样,可以将类和类之间的关系配置到配置文件中,而外观模式就是将他们的关系放在一个Facade类中,降低了类类之间的耦合度。

看一个简单的例子,UML类图如下所示:


ShapeMaker使用了一个具体的类,这个类能够帮助用户调用到所有类的操作。FacadeePatternDemo作为测试类,测试调用功能。

Shape.java

public interface Shape {
 void draw();
}

Rectangle.java

public class Rectangle implements Shape {
 @Override
 public void draw() {
 System.out.println("Rectangle::draw()");
 }
}

Square.java

public class Square implements Shape {
 @Override
 public void draw() {
 System.out.println("Square::draw()");
 }
}

Circle.java

public class Circle implements Shape {
 @Override
 public void draw() {
 System.out.println("Circle::draw()");
 }
}

创建Façade类,定义类ShapeMaker.java

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();
 }
}

定义测试类FacadePatternDemo

public class FacadePatternDemo {
 public static void main(String[] args) {
 ShapeMaker shapeMaker = new ShapeMaker();
 shapeMaker.drawCircle();
 shapeMaker.drawRectangle();
 shapeMaker.drawSquare(); 
 }
}

输出结果:

Circle::draw()
Rectangle::draw()
Square::draw()

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值