工厂模式是一种常见的设计模式,可以将对象的创建和使用分离,提高代码的灵活性和可维护性。下面是一个简单的 Java 工厂模式示例:

首先,定义一个接口:

public interface Shape {
    void draw();
}

然后,实现该接口的不同类:

public class Circle implements Shape {
    @Override
    public void draw() {
        System.out.println("Drawing a circle...");
    }
}

public class Rectangle implements Shape {
    @Override
    public void draw() {
        System.out.println("Drawing a rectangle...");
    }
}

public class Square implements Shape {
    @Override
    public void draw() {
        System.out.println("Drawing a square...");
    }
}

接着,定义一个工厂类,用于根据不同的参数创建不同的对象:

public 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;
    }
}

最后,使用工厂类创建对象:

Shape circle = ShapeFactory.createShape("CIRCLE");
circle.draw();

Shape rectangle = ShapeFactory.createShape("RECTANGLE");
rectangle.draw();

Shape square = ShapeFactory.createShape("SQUARE");
square.draw();

输出:

Drawing a circle...
Drawing a rectangle...
Drawing a square...
java写个工厂模式

原文地址: https://www.cveoy.top/t/topic/9Ws 著作权归作者所有。请勿转载和采集!

免费AI点我,无需注册和登录