请给我写一段java版委托与事件猫和老鼠且委托是类事件继承委托的代码
时间: 2024-05-30 14:14:58 浏览: 11
好的,以下是Java版委托与事件猫和老鼠且委托是类事件继承委托的代码:
// 定义事件接口
interface IEvent {
void execute();
}
// 定义事件委托
class EventDelegate {
private IEvent event;
public void setEvent(IEvent event) {
this.event = event;
}
public void invoke() {
if (event != null)
event.execute();
}
}
// 定义猫和老鼠类
class Cat {
private EventDelegate delegate;
public Cat() {
delegate = new EventDelegate();
}
public void addEventListener(IEvent event) {
delegate.setEvent(event);
}
public void catchMouse() {
System.out.println("猫抓到老鼠了!");
// 触发事件
delegate.invoke();
}
}
class Mouse {
public void run() {
System.out.println("老鼠逃跑了!");
}
}
// 定义猫抓老鼠事件
class CatchMouseEvent implements IEvent {
private Mouse mouse;
public CatchMouseEvent(Mouse mouse) {
this.mouse = mouse;
}
@Override
public void execute() {
// 老鼠逃跑
mouse.run();
}
}
// 测试代码
public class Test {
public static void main(String[] args) {
// 创建猫和老鼠
Cat cat = new Cat();
Mouse mouse = new Mouse();
// 注册事件
cat.addEventListener(new CatchMouseEvent(mouse));
// 猫抓老鼠
cat.catchMouse();
}
}
相关推荐
![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)