I want to create a class User
that will manipulate data on the user
table in my database. But I don't know if I should make it a Singleton or just bundle a bunch of static methods.
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...
}
I really don't know what would be the best approach here or the pros and cons of each of them. While the singleton class seems more elegant and cool, the static class API would be easier to use since I don't have to instantiate an object. Also it resembles me of mongoose, where such methods are static, eg: Model.create()
, Model.findById()
, and so on...
What do you think? Or I should do it in a completely different manner? Some context about the app:
Take a look at JPA, Spring Data with eclipselink as implementation or Hibernate. If it is just for educational purpouses have a look at the spring orm implementaions.
Users
and User
which could be defined like thatinterface User {
long id();
String name();
}
interface Users {
Iterable<User> iterate();
User create(String name);
void delete(User user);
Optional<User> findById(long id);
}
jdbc
or with help of a library such as jOOQ or jcabi-jdbc
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.