Skip to content

add notification example #3

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Open
wants to merge 1 commit into
base: master
Choose a base branch
from
Open
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
60 changes: 60 additions & 0 deletions observer/notification.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,60 @@
interface Subject {
registerObserver(o: Observer);
removeObserver(o: Observer);
notifyObservers(post: Post);
}

interface Observer {
getNotification(post: Post);
}

class Group implements Subject {
users: Observer[] = [];
posts: Post[] = [];
newPost(post: Post) {
this.posts.push(post); // Add a new post to the group
this.notifyObservers(post); // Notify each user in the group about the post
}
registerObserver(o: Observer) {
this.users.push(o);
}
removeObserver(o: Observer) {
let index = this.users.indexOf(o);
this.users.splice(index, 1);
}
notifyObservers(post: Post) {
for (let user of this.users)
if (user != post.user) // don't notify the user who posted the post himself
user.getNotification(post);
}

}

class Post {
constructor(public user: User, public content: String) {

}
}

class User implements Observer {
constructor(public name: String) {

}
getNotification(post: Post) {
console.log(`Notification for: ${this.name}\nUser: ${post.user.name} posted\nContent: ${post.content}\n`);
}
}

const myAwesomeFacebookGroup = new Group();

const user1 = new User("Kerollos Magdy");
const user2 = new User("Jane Smith");

myAwesomeFacebookGroup.registerObserver(user1);
myAwesomeFacebookGroup.registerObserver(user2);

const post1 = new Post(user1, "Hello Everybody!");
const post2 = new Post(user2, "Welcome to our awesome group Kerollos.");

myAwesomeFacebookGroup.newPost(post1);
myAwesomeFacebookGroup.newPost(post2);