我正在创建一个abstractFactory类,我希望能够将具体工厂作为参数发送。这样我就可以删除抽象类中的if / else链。
我的问题是我不知道如何将它强制转换回抽象类中的具体类,以便调用createVehicle()方法。
car = UniversalVehicleFactory.getFactory().createVehicle(CarFactory);
plane = UniversalVehicleFactory.getFactory().createVehicle(PlaneFactory);
在UniversalVehicleFactory里面我有方法createVehicle,这是我遇到问题的方法。我想要实现的是:获取参数,确定其类并将其转换为该类,然后调用其内部createVehicle类。
public Vehicle createVehicle(AbstractFactory factory) {
// I want to take factory,
// cast it to the concrete factory, and
// call createMethod() on the factory
return factory.getInstance().createVehicle();
}
非常感谢帮助解决这个问题!
答案 0 :(得分:3)
我会回答你的问题,但我很好奇为什么你想要一个通用工厂来调用抽象工厂的方法,如果确实你必须提供该工厂的实例作为参数;你最好直接调用抽象工厂的创建方法。
为此目的发明了仿制药。
interface Factory< T > {
T make();
}
public class CarFactory implements Factory< Car > {
Car make() { ... }
}
public class PlaneFactory implements Factory< Plane > {
Plane make() { ... }
}
public class UniversalVehicleFactory {
public < T extends Vehicle > T make( Factory< T > factory ) {
return factory.make();
}
}
你会注意到UniversalVehicleFactory没有实现Factory&lt; T&gt;。
答案 1 :(得分:1)
我认为您正在尝试在此处应用抽象工厂模式。这是我的解决方案:
您可以拥有界面VehicleFactory
和工厂类:
interface VehicleFactory {
Vehicle createVehicle();
}
class CarFactory implements VehicleFactory {
public Vehicle createVehicle() {
return new Car();
}
}
class PlaneFactory implements VehicleFactory {
public Vehicle createVehicle() {
return new Plane();
}
}
然后,如果您想集中所有工厂,您可以拥有UniversalVehicleFactory
:
class UniversalVehicleFactory {
private Map<Class<T extends VehicleFactory>, VehicleFactory> factories;
static {
factories = new HashMap<Class<T extends VehicleFactory>, VehicleFactory>();
factories.put(CarFactory.class, new CarFactory());
factories.put(PlaneFactory.class, new PlaneFactory());
}
public static VehicleFactory getFactory(Class<T extends VehicleFactory> factoryClass) {
return factories.get(factoryClass);
}
}
然后在你的代码中,使用可以像这样使用它:
Vehicle car = UniversalVehicleFactory.getFactory(CarFactory.class).createVehicle();
Vehicle plane = UniversalVehicleFactory.getFactory(PlaneFactory.class).createVehicle();
答案 2 :(得分:0)
以下是一些可能对您有帮助的通用代码:
public class A
{
public void paint(Graphics g)
{
}
}
public class B extends A
{
public static void main(String args[])
{
A a = new A();
B b = new B();
// This is the only one that won't work, because a is not an instance of b.
if(a instanceof B)
((B)a).draw(new Graphics());
if(b instanceof B)
((B)b).draw(new Graphcis());
if(a instanceof A)
((A)a).paint(new Graphics());
if(b instanceof A)
((A)b).paint(new Graphics());
}
public void draw(Graphics g)
{
}
}
instanceof
是在类型转换之前使用的一个很好的工具,可以避免错误。我希望这有帮助,如果它太笼统,你希望我更多地应用它,请告诉我。