代理模式

实验14:代理模式

本次实验属于模仿型实验,通过本次实验学生将掌握以下内容: 

1、理解代理模式的动机,掌握该模式的结构;

2、能够利用代理模式解决实际问题。

 

[实验任务一]:婚介所

婚介所其实就是找对象的一个代理,请仿照我们的课堂例子“论坛权限控制代理”完成这个实际问题,其中如果年纪小于18周岁,婚介所会提示“对不起,不能早恋!”,并终止业务。

类图

源代码

public interface MatchmakingService {
    void findPartner(Person person);
}

public class AgeVerificationProxy  implements MatchmakingService {
    private final MatchmakingService realService = new DirectMatchmakingService();

    @Override
    public void findPartner(Person person) {
        if (person.getAge() < 18) {
            System.out.println("Sorry, you cannot date!");
        } else {
            realService.findPartner(person);
        }
    }
}

public class DirectMatchmakingService implements MatchmakingService {
    @Override
    public void findPartner(Person person) {
        System.out.println(person.getName() + " is looking for a partner.");
    }
}

public class Person {
    private String name;
    private int age;

    public Person(String name, int age) {
        this.name = name;
        this.age = age;
    }

    public String getName() {
        return name;
    }

    public int getAge() {
        return age;
    }
}

public class Main {
    public static void main(String[] args) {
        Person youngPerson = new Person("Alice", 17);
        Person adultPerson = new Person("Bob", 20);

        MatchmakingService matchmakingService = new AgeVerificationProxy();

        matchmakingService.findPartner(youngPerson); // 应该打印出 "Sorry, you cannot date!"
        matchmakingService.findPartner(adultPerson); // 应该打印出 "Bob is looking for a partner."
    }
}

 

posted @   平安喜乐×  阅读(4)  评论(0编辑  收藏  举报
相关博文:
阅读排行:
· 25岁的心里话
· 闲置电脑爆改个人服务器(超详细) #公网映射 #Vmware虚拟网络编辑器
· 零经验选手,Compose 一天开发一款小游戏!
· 因为Apifox不支持离线,我果断选择了Apipost!
· 通过 API 将Deepseek响应流式内容输出到前端
点击右上角即可分享
微信分享提示