public class MapFactory implements IMapFactory { public IMapEngine createInstance(MapType type) { if(type==MapType.MapXtreme) return new MapXtremeEngine(); else if(type==MapType.VirtualEarth) return new VirtualEarth(); //....other code } }
我可以使用依赖注入框架在运行时按类型参数创建合适的映射引擎实现吗?
您的示例是条件实例化对象的正确模式。在任何需要创建实例的地方,接受 IMapFactory 在构造器中。
IMapFactory
动物工厂