面试题答案
一键面试基本步骤:
- 定义接口:定义一个接口,所有需要通过工厂创建的对象都实现这个接口。
- 创建实现类:创建接口的具体实现类。
- 创建工厂类:在工厂类中,使用反射机制根据类名动态创建对象。
- 调用工厂方法:通过调用工厂类的方法,传入需要创建对象的类名,获取相应的对象实例。
代码示例:
// 定义Shape接口
interface Shape {
void draw();
}
// Circle实现类
class Circle implements Shape {
@Override
public void draw() {
System.out.println("Drawing a Circle.");
}
}
// Rectangle实现类
class Rectangle implements Shape {
@Override
public void draw() {
System.out.println("Drawing a Rectangle.");
}
}
// 工厂类
class ShapeFactory {
public static Shape createShape(String className) {
try {
// 使用反射加载类
Class<?> shapeClass = Class.forName(className);
// 创建实例
return (Shape) shapeClass.newInstance();
} catch (ClassNotFoundException | InstantiationException | IllegalAccessException e) {
e.printStackTrace();
return null;
}
}
}
// 测试类
public class FactoryPatternWithReflectionExample {
public static void main(String[] args) {
Shape circle = ShapeFactory.createShape("Circle");
if (circle != null) {
circle.draw();
}
Shape rectangle = ShapeFactory.createShape("Rectangle");
if (rectangle != null) {
rectangle.draw();
}
}
}
在上述代码中:
Shape
接口定义了draw
方法。Circle
和Rectangle
类实现了Shape
接口。ShapeFactory
类的createShape
方法使用反射根据传入的类名创建Shape
的实例。- 在
main
方法中,通过ShapeFactory
创建Circle
和Rectangle
的实例并调用draw
方法。注意在实际使用时,传入createShape
方法的类名应包含完整的包名,如果类在默认包中则直接写类名。这里为了简洁,假设类在默认包中。