从Java中可能尚不存在的类实例中提取数据

时间:2015-09-30 17:02:04

标签: java design-patterns

在我的Data Structures with Java大学课程中,我们的任务是制作一个简单的社交网络

推荐给定接口定义的一个配置文件方法,它应该进入包含人员列表的配置文件对象数组。 这个实例接下来,选择一个,进入该实例的数组跟随列表并从那里返回一个配置文件作为有人要遵循的建议。

我真的不明白如何解决这个问题,因为我应该预料到一个尚未存在的课程实例。

我不希望任何回复的人为我做我的作业,但任何有关如何开始这项工作的指导将不胜感激。

1 个答案:

答案 0 :(得分:0)

这是一个(非常)简单的实现,您可以将其作为指南。

您的main方法:

public static void main(String args[])
{
    List<Profile> profiles;

    // You'll have to figure out how to load these yourself.
    // It sounds like this is probably the biggest part of the assignment.
    // It might not even be done here - maybe it's done in the Profile
    // class itself. Depends on how you want to implement it.
    profiles = loadProfiles(); 

    // Grab the first profile as a test. 
    testProfile = profiles.get(0);

    // Get whichever random profile was recommended.
    Profile recommendedProfile = testProfile.recommend();

    // Print them to the user. (You'll have to figure out how to do this best.)
    if (recommendedProfile != null)
        System.out.println("Test profile: " + testProfile.toString() +
                        " Recommended Profile: " + recommendedProfile.toString());
}

Profile类的可能实现:

public class Profile implements ProfileInterface
{
    // List of all friends.
    private List<Profile> friendProfiles;

    public Profile()
    {
        friendProfiles = new List<Profile>();
    }

    public Profile getRandomFriend()
    {
        if (friendProfiles.size() == 0)
            return null;
        else
            return friendProfiles.get((int)(Math.random() * friendProfiles.size())
    }

    public void addFriend(Profile friend)
    {
        friendProfiles.add(friend);
    }

    public Profile recommend()
    {
        Profile friend = this.getRandomFriend();
        return friend.getRandomFriend();
    }
}