帮我用java写一个工厂模式
时间: 2024-03-09 17:40:52 浏览: 18
工厂模式是一种创建型设计模式,它提供了一种创建对象的最佳方式。在工厂模式中,我们创建对象而不是直接实例化对象,这样可以使代码更加灵活和可维护。下面是一个简单的Java工厂模式示例:
```java
// 定义一个接口
interface Shape {
void draw();
}
// 实现接口的类
class Circle implements Shape {
@Override
public void draw() {
System.out.println("Circle.draw()");
}
}
class Square implements Shape {
@Override
public void draw() {
System.out.println("Square.draw()");
}
}
class Rectangle implements Shape {
@Override
public void draw() {
System.out.println("Rectangle.draw()");
}
}
// 工厂类
class ShapeFactory {
public Shape getShape(String shapeType) {
if (shapeType == null) {
return null;
}
if (shapeType.equalsIgnoreCase("CIRCLE")) {
return new Circle();
} else if (shapeType.equalsIgnoreCase("SQUARE")) {
return new Square();
} else if (shapeType.equalsIgnoreCase("RECTANGLE")) {
return new Rectangle();
}
return null;
}
}
// 使用工厂类创建对象
public class FactoryPatternDemo {
public static void main(String[] args) {
ShapeFactory shapeFactory = new ShapeFactory();
Shape shape1 = shapeFactory.getShape("CIRCLE");
shape1.draw();
Shape shape2 = shapeFactory.getShape("SQUARE");
shape2.draw();
Shape shape3 = shapeFactory.getShape("RECTANGLE");
shape3.draw();
}
}
```