gpt4 book ai didi

java - 从实现接口(interface)的对象调用方法

转载 作者:搜寻专家 更新时间:2023-11-01 02:27:34 26 4
gpt4 key购买 nike

我正在努力思考接口(interface),我希望它们是我问题的答案。

我为不同的游戏制作了插件和模组,有时类有 onUpdate 或 onTick 或其他可覆盖的方法。

如果我创建一个带有方法的接口(interface),然后创建其他实现该方法的类,然后创建这些类的实例,那么我如何才能同时从所有对象调用该方法?

最佳答案

您将看到观察者模式或类似的东西。它的要点是:在某个地方你必须保留一个类型为“你的接口(interface)”的列表(ArrayList 就足够了)。每次创建新对象时,将其添加到此列表中。之后,您可以在列表上执行循环并对其中的每个对象调用该方法。

稍后我将使用代码示例进行编辑。

public interface IMyInterface {
void DoSomething();
}

public class MyClass : IMyInterface {
public void DoSomething() {
Console.WriteLine("I'm inside MyClass");
}
}

public class AnotherClass : IMyInterface {
public void DoSomething() {
Console.WriteLine("I'm inside AnotherClass");
}
}


public class StartUp {
private ICollection<IMyInterface> _interfaces = new Collection<IMyInterface>();

private static void Main(string[] args) {
new StartUp();
}

public StartUp() {
AddToWatchlist(new AnotherClass());
AddToWatchlist(new MyClass());
AddToWatchlist(new MyClass());
AddToWatchlist(new AnotherClass());
Notify();
Console.ReadKey();
}

private void AddToWatchlist(IMyInterface obj) {
_interfaces.Add(obj);
}

private void Notify() {
foreach (var myInterface in _interfaces) {
myInterface.DoSomething();
}
}
}

输出:

I'm inside AnotherClass 
I'm inside MyClass
I'm inside MyClass
I'm inside AnotherClass

编辑:我刚刚意识到您将其标记为 Java。这是用 C# 编写的,但除了使用 ArrayList 而不是 Collection 之外没有真正的区别。

关于java - 从实现接口(interface)的对象调用方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18240947/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com