gpt4 book ai didi

java - 如何使用 java 创建通用且可重用的代码

转载 作者:行者123 更新时间:2023-12-01 11:51:08 25 4
gpt4 key购买 nike

我是java新手。我想做的是尝试创建可重用的泛型类。这是我的代码。

public interface Operation {
Boolean IsConnected();
Boolean ConnectionOpen();
Boolean ConnectionClose();
}

我的主课

public class MyConnectionManager extends MyWifi{

private MyWifi _wf;

public MyConnectionManager(MyWifi wf) {
// TODO Auto-generated constructor stub
_wf= wf;
}

public Boolean IsConnected() {
// TODO Auto-generated method stub
return _wf.IsConnected();
}


public Boolean ConnectionOpen() {
// TODO Auto-generated method stub
return _wf.ConnectionOpen();
}


public Boolean ConnectionClose() {
// TODO Auto-generated method stub
return _wf.ConnectionClose();
}
}




public class MyWifi implements Operation {

public Context _context =null;


@Override
public Boolean IsConnected() {
// TODO Auto-generated method stub

ConnectivityManager connManager = (ConnectivityManager) _context.getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo mWifi = connManager.getNetworkInfo(ConnectivityManager.TYPE_WIFI);

if (mWifi.isConnected()) {

return true;
}
return false;
}

但我希望它是通用的和可重用的,因为类型应该是可变的。例如,代替MyWifi,它可以是MyBlueTooth(实现相同的接口(interface))等等。

这是我们想要实现的目标。

MyWifi wf = new MyWifi();
//MyBlueTooth bl= new MyBlueTooth ();
MyConnectionManager<MyWifi> mn= new MyConnectionManager<MyWifi>(wf);
mn.IsConnected();

最佳答案

你的意思是这样的吗?

public class MyConnectionManager<E extends Operation>{

private E _wf;

public MyConnectionManager(E wf) {
// TODO Auto-generated constructor stub
_wf= wf;
}

public Boolean IsConnected() {
// TODO Auto-generated method stub
return _wf.IsConnected();
}


public Boolean ConnectionOpen() {
// TODO Auto-generated method stub
return _wf.ConnectionOpen();
}


public Boolean ConnectionClose() {
// TODO Auto-generated method stub
return _wf.ConnectionClose();
}

}

public class Starter {
public static void main(String[] args) {
MyBlueTooth bt = new MyBlueTooth();
MyWifi wf = new MyWifi();
MyConnectionManager<MyBlueTooth> test = new MyConnectionManager<MyBlueTooth>(bt);
MyConnectionManager<MyWifi> test2 = new MyConnectionManager<MyWifi>(wf);

}

}

关于java - 如何使用 java 创建通用且可重用的代码,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28815896/

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