Design Example: Social Network
A Social Network (like Facebook or LinkedIn) manages user profiles, friendships, and a dynamic feed of user-generated content and notifications.
Step 1: Requirements Gathering
Core Use Cases:
- Profile Management: Users can create profiles and update information.
- Connections: Users can follow or send friend requests to others.
- Posts: Users can share text, images, or links.
- Feed: A dynamic view showing posts from a user's connections.
- Notifications: Alerts for new likes, comments, or connection requests.
- Search: Find users or content by keywords or tags.
Relationship Types:
- One-Way (Follower): Like Twitter or Instagram.
- Two-Way (Friendship): Like Facebook (requires acceptance).
Step 2: Identify Core Objects
- User: The central entity with profile data and connections.
- Profile: Contains bio, photos, and settings.
- Post: Content created by a user (encapsulated in a
FeedItem). - Connection: Represents the link between two users.
- Notification: Alerts for specific actions.
- FeedService: Logic for generating a user's personalized feed.
Step 3: Design Class Diagram
Step 4: Implementation in TypeScript
class User {
private friends: Set<User> = new Set();
private posts: Post[] = [];
constructor(
public id: string,
public name: string,
public profile: Profile
) {}
public addFriend(friend: User) {
this.friends.add(friend);
friend.friends.add(this); // Assuming two-way friendship
// Notify through NotificationService
}
public createPost(content: string) {
const post = new Post(content, this);
this.posts.push(post);
return post;
}
}
class Post {
private comments: Comment[] = [];
private likes: User[] = [];
constructor(
public content: string,
public author: User
) {}
public addLike(user: User) {
this.likes.push(user);
// Notify author of the like
}
}Deep Dive: Observer Pattern for Feed & Notifications
The Observer Pattern is critical for social networks. When a user creates a post, their friends (the observers) should have their feeds updated (or receive notifications).
interface FeedObserver {
onNewPost(post: Post): void;
}
class FeedService implements FeedObserver {
onNewPost(post: Post) {
console.log(`Updating feed for followers of ${post.author.name}`);
// Add logic to persist in feed DB or Cache
}
}Wrap Up
Designing a Social Network involves complex Graph Relationships and high-frequency Status Updates. By decoupling the persistence of posts from the generation of feeds, you ensure the system remains responsive even with millions of concurrent users.
[!TIP] Use the Composite Pattern to handle different types of content (text, image, video) within a single
Postobject.