简单工厂模式uml类图常用例子水果
时间: 2024-06-07 17:04:00 浏览: 19
简单工厂模式是一种创建型设计模式,它提供了一个创建对象的最佳方式,但不暴露创建逻辑。在UML类图中,通常会用到一个"工厂"类来隐藏具体对象的创建细节,并返回相应的对象实例。这里以水果为主题,我们可以构建一个简单的示例:
1. **FruitFactory** (工厂类):这个类定义了一个静态方法或工厂方法,用于创建不同类型的水果对象。
```java
public class FruitFactory {
public static IFruit createFruit(String type) {
if (type.equals("Apple")) {
return new Apple();
} else if (type.equals("Banana")) {
return new Banana();
} else if (type.equals("Orange")) {
return new Orange();
}
// 可能添加默认处理或异常处理
throw new IllegalArgumentException("Invalid fruit type");
}
}
```
2. **IFruit** (接口):定义了所有水果的通用行为,比如"吃"。
```java
public interface IFruit {
void eat();
}
```
3. **Apple**、**Banana** 和 **Orange** (具体类):每个类都实现了IFruit接口,代表具体的水果类型。
```java
public class Apple implements IFruit {
@Override
public void eat() {
System.out.println("Eating an apple");
}
}
public class Banana implements IFruit {
@Override
public void eat() {
System.out.println("Eating a banana");
}
}
public class Orange implements IFruit {
@Override
public void eat() {
System.out.println("Eating an orange");
}
}
```
相关推荐
![-](https://csdnimg.cn/download_wenku/file_type_column_c1.png)
![-](https://csdnimg.cn/download_wenku/file_type_lunwen.png)
![-](https://csdnimg.cn/download_wenku/file_type_lunwen.png)
![-](https://csdnimg.cn/download_wenku/file_type_lunwen.png)
![-](https://csdnimg.cn/download_wenku/file_type_lunwen.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)