外观扩展模式代码实现
时间: 2023-09-18 09:12:13 浏览: 59
外观扩展模式(Facade Extension Pattern)是外观模式的一种扩展,它通过为外观类添加更多的方法来扩展外观的功能。下面是一个简单的外观扩展模式的代码实现:
```java
// 外观类
public class ShapeFacade {
private Circle circle;
private Rectangle rectangle;
private Square square;
public ShapeFacade() {
circle = new Circle();
rectangle = new Rectangle();
square = new Square();
}
public void drawCircle() {
circle.draw();
}
public void drawRectangle() {
rectangle.draw();
}
public void drawSquare() {
square.draw();
}
// 新增的方法
public void drawCircleAndRectangle() {
circle.draw();
rectangle.draw();
}
}
// 圆形类
public class Circle {
public void draw() {
System.out.println("Drawing Circle");
}
}
// 矩形类
public class Rectangle {
public void draw() {
System.out.println("Drawing Rectangle");
}
}
// 正方形类
public class Square {
public void draw() {
System.out.println("Drawing Square");
}
}
// 测试类
public class Test {
public static void main(String[] args) {
ShapeFacade facade = new ShapeFacade();
facade.drawCircleAndRectangle();
facade.drawSquare();
}
}
```
在这个例子中,我们新增了一个名为`drawCircleAndRectangle()`的方法,它可以一次性绘制圆形和矩形。通过这种方式,我们可以轻松地扩展外观类的功能,而不会对客户端代码产生影响。
相关推荐
![doc](https://img-home.csdnimg.cn/images/20210720083327.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![docx](https://img-home.csdnimg.cn/images/20210720083331.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)
![](https://img-home.csdnimg.cn/images/20210720083646.png)
![docx](https://img-home.csdnimg.cn/images/20210720083331.png)
![docx](https://img-home.csdnimg.cn/images/20210720083331.png)
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)
![docx](https://img-home.csdnimg.cn/images/20210720083331.png)
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)