我是关于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;
}
但我希望它是通用的和可重用的,因为类型应该是可更改的。例如,它可以是MyBlueTooth(它实现相同的接口),而不是MyWifi,等等。
这是试图实现的目标。
MyWifi wf = new MyWifi();
//MyBlueTooth bl= new MyBlueTooth ();
MyConnectionManager<MyWifi> mn= new MyConnectionManager<MyWifi>(wf);
mn.IsConnected();
答案 0 :(得分:1)
你的意思是这样的吗?
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);
}
}
答案 1 :(得分:0)
按如下方式更改MyConnectionManager:
public class MyConnectionManager<T extends Operation> implements Operation {
private T _op;
public MyConnectionManager(T op) {
// TODO Auto-generated constructor stub
_op = op;
}
public Boolean isConnected() {
// TODO Auto-generated method stub
return _op.isConnected();
}
public Boolean connectionOpen() {
// TODO Auto-generated method stub
return _op.connectionOpen();
}
public Boolean connectionClose() {
// TODO Auto-generated method stub
return _op.connectionClose();
}
public T getOperation() {
return _op;
}
}