首页 > 解决方案 > 负责数据库上的 CRUD 操作的类的最佳设计是什么?

问题描述

我想创建一个类User来操作user数据库中表上的数据。但我不知道是否应该将其设为 Singleton 或只是捆绑一堆静态方法。

class UserSingleton {
    private static instance;

    private UserSingleton() {
        // stablish connection and prepare statements
    }

    public static getInstance() {
        if (instance == null) {
            instance = new UserSingleton();
        }

        return instance;
    }

    public void create() {};
    public void delete() {};
    // and so on...
}

class UserStatic {
    public static initialize() {
         // Stablish connection and prepare statements. 
         // These properties would be static.
    }

    public static void create() {};
    public static void delete() {};
    // and so on...
}

我真的不知道这里最好的方法是什么,也不知道它们各自的优缺点。虽然单例类看起来更加优雅和酷,但静态类 API 会更容易使用,因为我不必实例化对象。它也类似于我的猫鼬,其中这些方法是静态的,例如:Model.create(), Model.findById(), 等等......

你怎么看?还是我应该以完全不同的方式来做?关于应用程序的一些上下文:

标签: javadesign-patternsarchitecture

解决方案


看看 JPA、Spring Data with eclipselink as implementation 或 Hibernate。如果只是出于教育目的,请查看 spring orm implementationaions。


推荐阅读