gpt4 book ai didi

java - 如何在Android中使用ormlite实现单例模式

转载 作者:行者123 更新时间:2023-11-29 05:38:28 25 4
gpt4 key购买 nike

我一直在 Android 中测试各种 orm,以便在我目前正在开发的应用程序中进行对象关系映射。

我做了一个类图,我发现在一些类中实现单例模式很有用。

正如单例模式所述,单例类必须将类的构造函数设为私有(private)以强制类的唯一实例。

从 ORMlite 帮助页面考虑这一点:

2.1.3 Adding a No-Argument-Constructor

After you have added the class and field annotations, you will also need to add a no-argument constructor with at least package visibility. When an object is returned from a query, ORMLite constructs the object using Java reflection and a constructor needs to be called.

如何使用 ORMLite 实现这种模式?,我将举一个例子:

ColectorPrincipal 类代表我的应用程序的用户,因为一次只有 1 个人使用该应用程序,我想确保一次只有 1 个此类实例。

public class ColectorPrincipal extends Persona {

@DatabaseField(index=true)
private String numeroColeccionActual;
private static ColectorPrincipal colectorPrincipal;
@DatabaseField(generatedId=true)
private int colectorPrincipalID;
@DatabaseField(foreign=true)
private ArrayList<Viaje> viajes;
@DatabaseField(foreign=true)
private ArrayList<Proyecto> proyectos;
@DatabaseField
private int tipoCapturaDatos;

/**
*
* @param usuario
* @param contraseña
*/
private ColectorPrincipal(String usuario, String contraseña){
super(usuario, contraseña);
setusuario(new Usuario(usuario, contraseña));
}

/**
*
* @param usuario
* @param contraseña
*/
public static ColectorPrincipal getColectorPrincipal(String usuario, String contraseña){
if (colectorPrincipal == null) {
colectorPrincipal=new ColectorPrincipal(usuario, contraseña);
}
return colectorPrincipal;
}
...

}

这个类有一些短暂的属性,还有一些持久的。

此类还从另一个名为 Persona 的类扩展而来,该类代表一个人,因此它具有姓名、电话、地址等数据......这些属性是持久的,但类 Person 不是持久的,因为我想存储来自两个类的数据在一个表中。

public class Persona {

@DatabaseField
private String nombres;
@DatabaseField
private String apellidos;
@DatabaseField
private String direccion;
@DatabaseField
private String telefono;
@DatabaseField
private String institucion;
private Usuario usuario;

public Persona(){

}
/**
*
* @param apellidos
* @param nombres
*/
public Persona(String apellidos, String nombres){

}
...
}

是否可以让 ORMLite 实例化类 tru 单例方法 getColectorPrincipal

最佳答案

我不能 100% 确定我了解您的要求。

I have made a class diagram and I have found it useful to implement the Singleton pattern in some classes.

让您的数据库实体成为单例确实没有意义。 ORMLite如果它从数据库中获取,则需要实例化 ColectorPrincipal 的实例。

This is one of my singleton classes I want to make persistent it represents an user of my app.

所以您在整个 JVM 中只有一个用户?我不明白。

如果你想从数据库中检索一个单例,你可以考虑一个包装类。包装类将强制执行单例,但它会使用另一个实体从数据库中初始化它的信息。

我不确定它是否有帮助,但 ORMLite 的一个新功能支持 ObjectFactory,它可以是 set on the DAO .该工厂允许您控制对象的实例化。这是 javadocs for ObjectFactory .

Is possible to use ORMLite without the public constructor?

构造函数不必是公开的。我相信包特权有效。

编辑:

听起来您正在寻找的是您希望一次登录一个用户。我只是在用户登录时在表中创建一个 UserLogin 的实例,然后在用户注销时将其删除。然后当用户登录时,您会看到 UserLogin 表中是否有任何有效条目。

关于java - 如何在Android中使用ormlite实现单例模式,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18601447/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com