我怎样才能避免这个 if 语句
我有一个枚举
public enum Vehicle {
CAR("CAR", "Car"), PUSHBIKE("PUSHBIKE", "PuschBike");
public boolean isCar()
{
...
}
public boolean isPushBike()
{
....
}
}
我有一个 2 DAO CarDAO
和 PushBikeDAO
正在实现一个 BaseDao
我有一个 JSF 托管 bean 这样的东西
public class JsfManagedBean {
private Vehicle vehicle;
private BaseDAO baseDao;
public void Search()
{
//I need to get rid of this if statement
if (vehicle.isCar())
{
baseDao = new CarDao;
baseDao.search();
}
else if(vehicle.isPushBike())
{
baseDao = new PushBike;
baseDao.search();
}
//Please Note each type of search is very different call to an other party's Jar
}
}
我试图摆脱这个如果可能通过使用泛型或任何适当的面向对象技术来声明 可能类似于
baseDao = new baseDaoImpl<getClass(vehicle.getcode())>
如果 vehicle.getcode()
返回字符串值 Car 我确实有一个模型类 Car。
只是大声思考(真的抓住了吸管:))。
这是 我的
I have an enum
public enum Vehicle {
CAR("CAR", "Car"), PUSHBIKE("PUSHBIKE", "PuschBike");
public boolean isCar()
{
...
}
public boolean isPushBike()
{
....
}
}
I have a 2 DAO CarDAO
and PushBikeDAO
which is are implementing a BaseDao
I have a JSF managed bean somthing like this
public class JsfManagedBean {
private Vehicle vehicle;
private BaseDAO baseDao;
public void Search()
{
//I need to get rid of this if statement
if (vehicle.isCar())
{
baseDao = new CarDao;
baseDao.search();
}
else if(vehicle.isPushBike())
{
baseDao = new PushBike;
baseDao.search();
}
//Please Note each type of search is very different call to an other party's Jar
}
}
I am trying to get rid of this if statement possibly by using generics or any proper OO technique
may be something like
baseDao = new baseDaoImpl<getClass(vehicle.getcode())>
where if vehicle.getcode()
returns String value Car I do have a model class Car.
Just loud thinking (clinching the straws really :)).
This is an offshot of this question of mine
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
向枚举添加一个方法,调用 new 并返回正确的 dao。
Add a method to the enum that calls new and returns the right dao.
让每个枚举常量定义它们各自的 DAO 类:
这样,您可以使用:
看一下 Factory方法模式和策略模式(如果您想知道) 更多的。枚举是我使用后者的首选方式。
Let each of the enum constants define their respective DAO classes:
This way, you can use:
Take a look at the Factory method pattern and the Strategy pattern if you'd like to know more. Enums are my preferred way to use the latter.
我会使用工厂方法,如下所示:
I would use a factory method, like so:
除非您对 DAO 对象有更多用途,否则可以缩短此代码:
有两种选择,我将继续使用
if
语句。如果您确实有很多车辆变体,则可以使用由枚举值作为键的哈希表并存储 DAO 类:不在这里使用反射并不那么慢。
Unless you have more uses for DAO objects, you could make this code shorter:
With two alternatives, I'd stay with the
if
statement. If you had really many variants of vehicles, you could use a hash table keyed by the enum values and storing the DAO classes:Reflection is not that slow not to use here.