我已经在我的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"
    }));


我目前面临的问题是它总是重复最后一行中的数据。
如果有人可以帮助我,我将非常感激。

最佳答案

您的设计中存在一个市长缺陷。
我猜想OwnerML类应该是数据的容器。将其实现为Singleton没有任何意义。

每次在使用数据库结果填充OwnerML.getInstance()列表时调用OwnerList时,您都在引用同一类的实例(这是Singleton的本质)。
结果,您将始终有一个列表,其中包含对同一对象(单个)的多个引用。

您应该忘了将Singleton用作数据容器(我们称其为“数据传输对象-DTO”)。
实际上,Singleton几乎对任何事情都不有用(值得注意的例外是:日志记录子系统,单个硬件资源的处理程序,以及可能是Spring式的bean工厂)。

简而言之:
公开OwnerML构造函数,然后替换
OwnerML OwnerData =OwnerML.getInstance();

OwnerML OwnerData = new OwnerML();

===编辑===

@Anton的评论是第一的,他是对的。下次我应该键入更快:)

10-06 02:11