有没有办法有效地审计Java中对象的统计属性?



>假设我有一个类 Person,我创建了 10 个 Person 实例,每个实例都有几个不同的属性,例如enum Gender{MALE, FEMALE}enum Profession{CEO, POLICE, TEACHER}等。

而且我必须以某种方式随机创建许多具有随机属性的人,并使用专用类来审核创建人员属性的统计信息。

因此,最终,我需要生成一个属性列表,并相应地使用一些统计信息,例如"FEMALE: [number]POLICE: [number],..."。

目前,我计划将各种人员的属性计数添加为一堆新属性到审计类中,例如"femaleCount intpoliceCount int, ...",然后根据生成的人操纵计数。

但是,我为每个人获得了 10 个左右的属性,所以我想知道是否有更好的方法来做到这一点。

感谢您的阅读。

下面有一种可能的方法,但不要说它是唯一的也不是最好的。
这仅取决于目的和您的设计。
其他选择可能是将所有Persons存储在数据结构List中,并根据特定时间的数据计算统计数据(此处也更新/删除(

仅添加正在计数的版本...

public class Statistic
{

private static Statistic s=null;
public int countPerson;
public int countMale;
public int countFemale;
public static Statistic getInstance()
{
if(s==null) 
s =  new Statistic(0, 0, 0);
return s;
}
public static Statistic getInstace(int cP,int cM, int cF)
{
if(s==null) 
s = new Statistic(cP, cM, cF);
return s;
}
//do whatever init wanted
private Statistic(int cP,int cM, int cF)
{
countPerson = cP;
countMale = cM;
countFemale = cF;
}

public String toString()
{
return "Total="+countPerson+", Male="+countMale+", Female=" + countFemale;
}

}

public class Person
{
public int id;
public String name;
public Gender g;
public Profession p;
public enum Gender{MALE, FEMALE};
public enum Profession{CEO, POLICE, TEACHER}
Person(int id,String name, Gender g, Profession p)
{
this.id = id;
this.name = name;
this.g = g;
this.p = p;
Statistic.getInstance().countPerson++;
if(g.equals(Gender.MALE))
{
Statistic.getInstance().countMale++;
}
else
{
Statistic.getInstance().countFemale++;
}
}

}

public class TestStat {
public static void main(String[] args) 
{
//cPersons,cMale,cFemale - init
Statistic.getInstace(10, 5, 5);
System.out.println(Statistic.getInstance());
new Person(1,"Male",Person.Gender.MALE, Person.Profession.TEACHER);
System.out.println(Statistic.getInstance());
new Person(2,"Female",Person.Gender.FEMALE, Person.Profession.CEO);
System.out.println(Statistic.getInstance());

}
}

输出

//custom start from (10,5,5) based on Singleton Custom Constructor
Total=10, Male=5, Female=5
//start update counters
Total=11, Male=6, Female=5
Total=12, Male=6, Female=6

三思而后行,也许最好与Persons保持ListSingleton并使每次都成为new Computation- 从Singleton而不是Person. 关于一个人Delete可以翻译为"从一家公司转移到其他公司",然后它不会反映在统计中。
即便如此,在当前,您也可以在人身上添加一个delete method,该可以通过调整StatisticminusPerson-Instancenull来反映。
此外,您可以根据需要更新设计。

最新更新