工厂模式是一种创建对象的设计模式,它将对象的创建封装在一个工厂类中,通过调用工厂类的方法来创建对象。工厂模式可以隐藏对象的创建细节,降低耦合性,并提供灵活性。
在使用工厂模式创建对象时,首先需要定义一个工厂类,该类负责创建对象。工厂类通常包含一个静态方法,该方法根据不同的条件创建不同的对象。
以下是一个示例代码,展示如何使用工厂模式创建对象:
// 定义一个接口
interface Shape {
void draw();
}
// 实现接口的具体类
class Circle implements Shape {
@Override
public void draw() {
System.out.println("Circle");
}
}
class Rectangle implements Shape {
@Override
public void draw() {
System.out.println("Rectangle");
}
}
class Square implements Shape {
@Override
public void draw() {
System.out.println("Square");
}
}
// 定义一个工厂类
class ShapeFactory {
// 根据传入的参数创建对象
public static Shape createShape(String shapeType) {
if (shapeType == null) {
return null;
}
if (shapeType.equalsIgnoreCase("CIRCLE")) {
return new Circle();
} else if (shapeType.equalsIgnoreCase("RECTANGLE")) {
return new Rectangle();
} else if (shapeType.equalsIgnoreCase("SQUARE")) {
return new Square();
}
return null;
}
}
// 使用工厂类创建对象
public class FactoryPatternDemo {
public static void main(String[] args) {
Shape circle = ShapeFactory.createShape("CIRCLE");
circle.draw(); // 输出:Circle
Shape rectangle = ShapeFactory.createShape("RECTANGLE");
rectangle.draw(); // 输出:Rectangle
Shape square = ShapeFactory.createShape("SQUARE");
square.draw(); // 输出:Square
}
}
在上述示例中,定义了一个Shape接口,以及三个实现了Shape接口的具体类Circle、Rectangle和Square。然后定义了一个ShapeFactory工厂类,该类根据传入的参数创建不同的对象。
在主函数中,通过调用ShapeFactory类的静态方法createShape来创建不同的对象,并调用其draw方法输出对象的类型。

被折叠的 条评论
为什么被折叠?



