Laravel  
laravel
文档
数据库
架构
入门
php技术
    
Laravelphp
laravel / php / java / vue / mysql / linux / python / javascript / html / css / c++ / c#

java factory

作者:旭旭移日   发布日期:2025-09-21   浏览:92

// Java Factory Pattern Example

// Step 1: Create an interface
interface Shape {
    void draw();
}

// Step 2: Create concrete classes implementing the above interface
class Rectangle implements Shape {
    public void draw() {
        System.out.println("Inside Rectangle::draw() method.");
    }
}

class Square implements Shape {
    public void draw() {
        System.out.println("Inside Square::draw() method.");
    }
}

class Circle implements Shape {
    public void draw() {
        System.out.println("Inside Circle::draw() method.");
    }
}

// Step 3: Create a Factory to generate object of concrete class based on given information.
class ShapeFactory {
    // use getShape method to get object of type shape 
    public Shape getShape(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;
    }
}

// Step 4: Use the Factory to get objects of Concrete class/shape by passing an information such as type.
class FactoryPatternDemo {
    public static void main(String[] args) {
        ShapeFactory shapeFactory = new ShapeFactory();

        // get an object of Circle and call its draw method.
        Shape shape1 = shapeFactory.getShape("CIRCLE");
        // call draw method of Circle
        shape1.draw();

        // get an object of Rectangle and call its draw method.
        Shape shape2 = shapeFactory.getShape("RECTANGLE");
        // call draw method of Rectangle
        shape2.draw();

        // get an object of Square and call its draw method.
        Shape shape3 = shapeFactory.getShape("SQUARE");
        // call draw method of Square
        shape3.draw();
    }
}

解释说明:

  1. 接口定义Shape 接口定义了一个 draw() 方法,所有具体的形状类(如 Rectangle, Square, Circle)都实现了这个接口。
  2. 具体实现类Rectangle, Square, 和 Circle 类分别实现了 Shape 接口,并提供了各自的 draw() 方法实现。
  3. 工厂类ShapeFactory 类包含一个 getShape 方法,根据传入的字符串参数返回相应的形状对象。
  4. 客户端代码FactoryPatternDemo 类展示了如何使用工厂模式来获取不同类型的形状对象,并调用它们的 draw() 方法。

通过这种方式,工厂模式可以将对象的创建逻辑封装在工厂类中,使得客户端代码不需要关心具体的对象创建过程,从而提高了代码的灵活性和可维护性。

上一篇:java 创建list

下一篇:java int的最大值

大家都在看

java连接数据库的代码

java djl

ubuntu 卸载java

java读取excel中的图片

java新建

java sort用法

java collections.sort

java file类的方法

java发送qq邮件

java 判断

Laravel PHP 深圳智简公司。版权所有©2023-2043 LaravelPHP 粤ICP备2021048745号-3

Laravel 中文站