设计推特
面向对象设计
整体框架
class Twitter {
private static int timestamp = 0;
private static class Tweet {
}
private static class User {
}
/* 还有那几个 API 方法 */
public void postTweet(int userId, int tweetId) {
}
public List<Integer> getNewsFeed(int userId) {
}
public void follow(int followerId, int followeeId) {
}
public void unfollow(int followerId, int followeeId) {
}
}
之所以要把 Tweet 和 User 类放到 Twitter 类里面,是因为 Tweet 类必须要用到一个全局时间戳 timestamp,而 User 类又需要用到 Tweet 类记录用户发送的推文,所以它们都作为内部类。不过为了清晰和简洁,下文会把每个内部类和 API 方法单独拿出来实现。
Tweet 类
class Tweet {
private int id;
private int time;
private Tweet next;
// 需要传入推文内容(id)和发文时间
public Tweet(int id, int time) {
this.id = id;
this.time = time;
this.next = null;
}
}
User 类
// static int timestamp = 0
class User {