我在我的java程序中创建了以下单例设计模式
private int OwnerId;
private String OwnerName;
private String OwnerNic;
private String OwnerAddress;
private int OwnerTele;
private String OwnerEmail;
private String OwnerDate;
private static OwnerML instance = new OwnerML();
// make the coosntructor private so that this class cannot be instantiated
private OwnerML(){}
// get the only object available
public static OwnerML getInstance() {
return instance;
}
public int getOwnerId() {
return OwnerId;
}
public void setOwnerId(int OwnerId) {
this.OwnerId = OwnerId;
}
我使用了一个单独的方法来调用view方法
public ArrayList<OwnerML> SelectOwnerData()
{
ArrayList<OwnerML> OwnerList = new ArrayList<OwnerML>();
try {
Connection con = DB.connect();
String selectQ = "select * from owners";
PreparedStatement ps2 = con.prepareStatement(selectQ);
ResultSet rs = ps2.executeQuery();
while (rs.next())
{
OwnerML OwnerData =OwnerML.getInstance();
OwnerData.setOwnerId(rs.getInt(1));
OwnerData.setOwnerName(rs.getString(2));
OwnerData.setOwnerNic(rs.getString(3));
OwnerData.setOwnerAddress(rs.getString(4));
OwnerData.setOwnerTele(rs.getInt(5));
OwnerData.setOwnerEmail(rs.getString(6));
OwnerList.add(OwnerData);
}
rs.close();
ps2.close();
con.close();
通过使用以下方法,我在我的界面中调用它
ArrayList<OwnerML> ownerList = new OwnerCL().SelectOwnerData();
Object obj[][] = new Object[ownerList.size()][6];
int x = 0;
for (OwnerML t : ownerList) {
obj[x][0] = t.getOwnerId();
obj[x][1] = t.getOwnerName();
obj[x][2] = t.getOwnerNic();
obj[x][3] = t.getOwnerAddress();
obj[x][4] = t.getOwnerTele();
obj[x][5] = t.getOwnerEmail();
x++;
}
ownerTbl.setModel(new javax.swing.table.DefaultTableModel(obj,new Object[]{
"OwneID", "Name", "Nic", "Address", "Tele", "Email", "Date", "VehicleID", "Type", "Model", "Year", "RegNumber"
}));
我目前面临的问题是它总是重复最后一行中的数据。 如果有人能帮助我,我会非常感激。
答案 0 :(得分:1)
您的设计中存在一个市长缺陷。
我猜OwnerML
类应该是数据的容器。将它作为Singleton实现是没有意义的。
每当您使用数据库中的结果填充OwnerML.getInstance()
列表时调用OwnerList
,您就会引用相同的类&#39;实例(这是Singleton的本质)
因此,您将始终拥有一个列表,其中包含对同一对象的多个引用(单例)。
您应该忘记使用Singleton作为数据容器(让我们称之为数据传输对象 - DTO)。 事实上,Singleton很少用于任何事情(特别是例外:日志子系统,单一硬件资源的处理程序,也许是Spring-ish bean工厂)。
简而言之:
将OwnerML
构造函数设为public,然后替换为
OwnerML OwnerData =OwnerML.getInstance();
与
OwnerML OwnerData = new OwnerML();
=== EDIT ===
@Anton的评论是第一次,他是对的。我下次应该打字更快:)