我有一个Worker
接口,有一个方法:
interface Worker {
public void work()
}
我有两个实现Worker
,
class RoadWorker implements Worker {
public void setPropertyA() {}
public void work() {}
}
另一个,
class GardenWorker implements Worker {
public void setPropertyB() {}
public void work() {}
}
在我的Application
类中 - 基于一些输入标志 - 我想实例化一种特定类型的工作者......
class Application {
// flag
String whichWorker = "Road";
// instantiate
if (whichWorker == "Road") {
RoadWorker worker = new RoadWorker();
worker.setPropertyA();
} else {
GardenWorker worker = new GardenWorker();
worker.setPropertyB();
}
// use
worker.work(); <----- OF COURSE THIS DOES NOT WORK (no reference)
所以,我试过了 -
class Application {
// flag
String whichWorker = "Road";
Worker worker;
// instantiate
if (whichWorker == "Road") {
worker = new RoadWorker();
worker.setPropertyA(); <----- DOES NOT WORK
} else {
worker = new GardenWorker();
worker.setPropertyB(); <----- DOES NOT WORK
}
// use
worker.work();
我的问题是 - 我如何设计我的程序来达到这个要求?我知道一个原始选项是将worker定义为Object
但是我将不得不做很多我不想要的类型转换。有人可以建议吗?
答案 0 :(得分:2)
Worker anyworker = null;
if ("Road".equals( whichWorker )) {
RoadWorker worker = new RoadWorker();
worker.setPropertyA();
anyworker = worker;
} else {
GardenWorker worker = new GardenWorker();
worker.setPropertyB();
anyworker = worker;
}
或者传递子类构造函数中的特定属性值。
答案 1 :(得分:1)
使用构造函数设置属性或工厂模式。
第一种解决方案更简单但有其局限性:
interface Worker {
public void work()
}
class RoadWorker implements Worker {
RoadWorker(PropertyA property) {
this.property = property;
}
}
void foo() {
Worker worker = null;
if (whichWorker.equals("road")) {
worker = new RoadWorker(property);
}
worker.work();
}
两个旁注:
如果你更灵活,那么factory method pattern可能更合适。
答案 2 :(得分:1)
您可以让worker实现的构造函数执行特定于这些实现的操作。
RoadWorker:
class RoadWorker implements Worker {
public RoadWorker() {
this.setPropertyA();
}
public void setPropertyA() {}
public void work() {}
}
GardenWorker:
class GardenWorker implements Worker {
public GardenWorker() {
this.setPropertyB();
}
public void setPropertyB() {}
public void work() {}
}
然后删除对if语句中setProperty
方法的调用:
class Application {
// flag
String whichWorker = "Road";
Worker worker;
// instantiate
if (whichWorker.equals("Road")) {
worker = new RoadWorker();
} else {
worker = new GardenWorker();
}
// use
worker.work();
注意:我将whichWorker == "Road"
更改为whichWorker.equals("Road")
,因为对于字符串比较,您需要使用equals
而不是==
。
答案 3 :(得分:0)
设置其属性时,可以使用适当的instanciation类型转换worker实例。
例如
if (whichWorker == "Road") {
worker = new RoadWorker();
((RoadWorker)worker).setPropertyA();
} else {
worker = new GardenWorker();
((GardenWorker)worker).setPropertyB();
}
这应该有效