java 外观模式 例子
时间: 2023-05-21 08:02:06 浏览: 51
外观模式是一种结构型设计模式,它提供了一个简单的接口,隐藏了一组复杂的子系统接口,使得客户端能够更加方便地使用这些子系统。
下面是一个 Java 外观模式的例子:
```
// 子系统接口
interface Shape {
void draw();
}
class Rectangle implements Shape {
@Override
public void draw() {
System.out.println("Rectangle::draw()");
}
}
class Square implements Shape {
@Override
public void draw() {
System.out.println("Square::draw()");
}
}
class Circle implements Shape {
@Override
public void draw() {
System.out.println("Circle::draw()");
}
}
// 外观类
class ShapeMaker {
private Shape rectangle;
private Shape square;
private Shape circle;
public ShapeMaker() {
rectangle = new Rectangle();
square = new Square();
circle = new Circle();
}
public void drawRectangle() {
rectangle.draw();
}
public void drawSquare() {
square.draw();
}
public void drawCircle() {
circle.draw();
}
}
// 客户端代码
public class Main {
public static void main(String[] args) {
ShapeMaker shapeMaker = new ShapeMaker();
shapeMaker.drawRectangle();
shapeMaker.drawSquare();
shapeMaker.drawCircle();
}
}
```
在这个例子中,我们定义了三个子系统接口:`Rectangle`、`Square` 和 `Circle`,它们都实现了 `Shape` 接口。然后我们定义了一个外观类 `ShapeMaker`,它包含了这三个子系统接口的实例,并提供了三个简单的方法 `drawRectangle()`、`drawSquare()` 和 `drawCircle()`,用于调用子系统接口的 `draw()` 方法。
客户端代码只需要创建一个 `ShapeMaker` 实例,然后调用它的方法即可,而不需要了解子系统接口的具体实现。这样就实现了外观模式的目的,简化了客户端代码的复杂度。
相关推荐
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![docx](https://img-home.csdnimg.cn/images/20210720083331.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)
![doc](https://img-home.csdnimg.cn/images/20210720083327.png)
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)