24.11.29
实验14:代理模式
本次实验属于模仿型实验,通过本次实验学生将掌握以下内容:
1、理解代理模式的动机,掌握该模式的结构;
2、能够利用代理模式解决实际问题。
[实验任务一]:婚介所
婚介所其实就是找对象的一个代理,请仿照我们的课堂例子“论坛权限控制代理”完成这个实际问题,其中如果年纪小于18周岁,婚介所会提示“对不起,不能早恋!”,并终止业务。
实验要求:
1. 提交类图;
2. 提交源代码;
3. 注意编程规范。
- 类图:

- 源代码:
// 抽象主题接口
interface Matchmaking {
void findPartner(int age); // 找对象方法,传入年龄
}
// 真实主题类
class RealMatchmaking implements Matchmaking {
@Override
public void findPartner(int age) {
System.out.println("正在为您匹配合适的对象...");
}
}
// 代理类
class ProxyMatchmaking implements Matchmaking {
private RealMatchmaking realMatchmaking;
public ProxyMatchmaking() {
this.realMatchmaking = new RealMatchmaking(); // 初始化真实对象
}
@Override
public void findPartner(int age) {
if (age < 18) {
System.out.println("对不起,不能早恋!");
} else {
System.out.println("欢迎使用婚介服务!");
realMatchmaking.findPartner(age); // 调用真实服务
}
}
}
public class Client{
public static void main(String[] args) {
Matchmaking proxy = new ProxyMatchmaking();
System.out.println("用户1:年龄16岁");
proxy.findPartner(16); // 输出:对不起,不能早恋!
System.out.println("\n用户2:年龄22岁");
proxy.findPartner(22); // 输出:欢迎使用婚介服务!正在为您匹配合适的对象...
}
}
浙公网安备 33010602011771号