请结合享元模式写一个功能案例供我学习享元模式
时间: 2023-05-31 07:07:53 浏览: 64
好的,以下是一个简单的享元模式功能案例:
假设有一个学生管理系统,其中有很多个班级,每个班级里面有很多个学生。我们可以采用享元模式来优化该系统。
首先,我们定义一个抽象的"学生"类,该类包含学生的基本信息,例如姓名、性别、年龄等等。接着,我们定义一个"学生工厂"类,负责生产学生对象并进行管理。"学生工厂"类中包含一个学生对象池,该池中存储之前创建的学生对象。每当需要创建一个新的学生对象时,"学生工厂"类会首先检查对象池中是否已经存在这个学生对象,如果存在,则直接返回该对象,否则创建一个新的对象并加入到对象池中。
实现代码如下:
抽象的学生类:
```
public abstract class Student {
protected String name;
protected String gender;
protected int age;
public Student(String name, String gender, int age) {
this.name = name;
this.gender = gender;
this.age = age;
}
public abstract void showInfo(); // 显示学生信息
}
```
具体的学生类:
```
public class ConcreteStudent extends Student {
public ConcreteStudent(String name, String gender, int age) {
super(name, gender, age);
}
@Override
public void showInfo() {
System.out.println("姓名:" + name + ",性别:" + gender + ",年龄:" + age);
}
}
```
学生工厂类:
```
import java.util.HashMap;
import java.util.Map;
public class StudentFactory {
private static Map<String, Student> pool = new HashMap<>();
public static Student getStudent(String name, String gender, int age) {
String key = name + gender + age;
Student student = pool.get(key);
if (student == null) {
student = new ConcreteStudent(name, gender, age);
pool.put(key, student);
}
return student;
}
}
```
在这个案例中,我们将学生对象作为享元对象,实现了对象的共享和重复利用。这样可以减少系统中对象的数量,降低内存开销,提高系统的性能。同时,学生工厂类还可根据需要进行对象池的管理,以确保对象的有效使用。
相关推荐
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![](https://img-home.csdnimg.cn/images/20210720083646.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)
![](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)