Ich überarbeite gerade einen Chat-Bot, den ich in Java erstellt habe, der sich mit mehreren verschiedenen Websites verbindet, und muss abhängig von der Plattform verschiedene Aktionen ausführen. Jede Plattform muss gleich funktionieren, wird aber einfach anders ausgeführt, abhängig von der Website-API.Java - Verwenden von Anmerkungen zum Aufrufen verschiedener Funktionen?
Zur Erläuterung werde ich verwenden Plattformen Alpha
und Beta
(Plattformen Plattformen IRC/Websocket ist, nicht Betriebssysteme/Geräte.)
public class MyMainClass {
public static void main(String[] args) {
sharedClass Alpha = new sharedClass("Alpha");
sharedClass Beta = new sharedClass("Beta");
}
}
SUBKLASSE
/* To do so, I have created a shared class */
public class sharedClass {
public String platformName = null;
public sharedClass(String name) {
this.platformName = name;
}
/* Both platforms use many shared
* functions, so I want to keep them
* in the same class file, rather than
* separating them.
*/
public String sharedFunctionA() { return null; }
public String sharedFunctionB() { return null; }
/* ... */
/* However, some functions that touch
* on the APIs required picking out
* different information.
*
* My goal is to get rid of these functions
* so I can leave them as-is and not have
* to add a new else to it every time I
* add a new platform.
*/
public String nitpickFunction() {
/* Many similar functions exist,
* where I am required to use more
* than just two platforms.
*/
if (this.platformName.equals(/* Platform-Alpha */)) {
/* Do Stuff For Platform Alpha */
} else if (this.platformName.equals(/* Platform-Beta */)) {
/* Do Stuff For Platform Beta */
} /* else if (Platform-Gamma) {
} else if (Platform-Delta) {
} else if (Platform-Epsilon) {
} else if (Platform-Zeta) {
} ...
*/
}
public String properFunction() {
/* My hope (New To Creating Annotations)
* is to do something similar to the following,
* so that I can call what would have been inside
* an if/else block, from the platforms respective
* class file.
*/
@DoPlatformNitpick
myNitpickFunction();
/*
* Or just something like this
*/
MyPlatform mySelectedFunction = new MyPlatform();
mySelectedFunction.nitpick();
/* However I believe that would require my
* Alpha and Beta platforms to use the same
* class type.
*/
}
/* Please ignore the possible NullPointerException,
* this is just an example.
*/
}
Kann mir jemand erklären, wie ich das durchziehen kann oder ob es gerade ist möglich oder nicht? Kommentar, wenn ich besser erklären muss. Ich habe ein bisschen gesucht, um zu sehen, ob ich etwas Ähnliches finden könnte, aber vielleicht etwas verpasst.
Sie sollten wahrscheinlich die Klasse für jede Plattform erweitern und die entsprechenden Methoden überschreiben. – 4castle
Bitte überprüfen Sie, welche "Schnittstelle" und abstrakte Klasse in Java sind – jny