[英]Java - best option to select callable method at runtime by argument class
這是一些不同類的服務處理對象的示例:
class SomeService {
void method(A a) {
/* A class logic here */
}
void method(B b) {
/* B class logic here */
}
...
void method(Z z) {
/* Z class logic here */
}
public <T> void method(T anyClass) {
/* Some heavy common logic here */
/* (1) Here I want to call method corresponding class of
"anyClass" parameter */
}
}
我method(T anyClass)
在其他組件中調用method(T anyClass)
。 在(1)中選擇並調用私有方法之一的最佳選擇是什么?
您的問題似乎與Startegy設計模式非常接近。
策略設計模式定義 (來源: https : //en.wikipedia.org/wiki/Strategy_pattern )
在計算機編程中,策略模式(也稱為策略模式)是一種軟件設計模式,可以在運行時選擇算法的行為。 策略模式
- 定義了一系列算法,
- 封裝每種算法,並
- 使算法在該系列中可以互換。
一種實現方法是利用MBassador事件總線,作為免責聲明,我會說這可能不是最好的方法,盡管它可以工作。 一旦某個類訂閱了總線,就可以使用publish()
將“消息”(可以是標准類)發送到總線。 事件總線將使用@Handler
批注查找偵聽器方法。 偵聽器消息期望的參數類型將使總線能夠選擇正確的調用方法。
在此示例中, Class1
和Class2
是空類,它們都擴展了一個稱為AbstractClass
的空抽象類
主類示例
import net.engio.mbassy.bus.MBassador;
import net.engio.mbassy.bus.config.BusConfiguration;
public class SomeService
{
private static MBassador<AbstractClass> bus;
public static void main(String[] args)
{
//Creates the bus, and passes that instance of the
//bus into the Methods class
bus = new MBassador<>(BusConfiguration.Default());
Methods methodsClass = new Methods(bus);
sendMessage(new Class1());
sendMessage(new Class2());
}
//This is equivalent to your method(T anyClass)
public static void sendMessage(AbstractClass anyClass)
{
//Do common logic
SomeService.bus.publish(anyClass);
}
}
包含單個方法的類
import net.engio.mbassy.bus.MBassador;
import net.engio.mbassy.listener.Handler;
public class Methods
{
MBassador<AbstractClass> bus;
public Methods(MBassador<AbstractClass> busIn)
{
//Subscribe to the bus, so that you can listen to
//messages that are published onto it
this.bus = busIn;
this.bus.subscribe(this);
}
//Class specific methods, called by the bus
//due to the message published in SomeService.sendMessage()
@Handler (rejectSubtypes = false)
public void doThing(Class1 cl)
{
System.out.println("Class 1");
}
@Handler (rejectSubtypes = false)
public void doThing(Class2 cl)
{
System.out.println("Class 2");
}
}
在這種情況下,控制台輸出為
1類
2級
希望對您有所幫助,請隨時在評論中進行任何澄清
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.