What design-pattern I should use in my notification system? - email

Which design-pattern I should use in this case:
I have a rest API notification system.
I can notify by Email
notify by push;
notify by WhatsApp.
And I want to implement more technologies, and I do not want to modify the core, I want to add only modules to the system. For example, adding Telegram Messages, Twitter messages, or another email provider.
Any recommendation?

According to your problem statement, two different types of design patterns will be involved:
1) Strategy Pattern: It will define the notification strategy based on the contexts like email, push, whatsapp, etc.
3) Observer Pattern: It will perform the publisher and subscribers operation will the behavior of loose coupling. It will automatically notify to subcriber.
You can also integrate RabbitMq somewhere for queuing and on time pushing messages.

The case you explained is like strategy design pattern . You can use strategy design pattern and have an interface and a class for your each system that implement your interface. These are links that can help you :
tutsplus design ptterns
designpatternsphp

For a notification system I would suggest you using the Observer pattern. The message you receive should be inside your Subject. Subject should allow any number of Observers to attach. When a message is received, the subject should notify all the observers. Then Observers can read the state/message from the subject and act upon it. I am not pretty much clear about your usecase. But this would do the job.

To me seems a PUB-SUB model or a Observer pattern is best, extension in the form of subscriber registered to publisher works well as subscriber can have their own implementation details abstracting away from core notification service.

Strategy Pattern:
Define a family of algorithms (your types of notifications), encapsulate each one (each type of notification), and make them interchangeable (with a common abstraction). Strategy lets the algorithm vary independently from the clients that use it.
Capture the abstraction in an interface, bury implementation details in derived classes.
Each time you want to add different types of notification you will add new strategies (Twitter, Telegram, ecc)

observer - observable pattern suits for you. if u use any frameworks ( spring in java) built in futures - like event listener & publisher - this really reduces ur burden of implementations.
i hope u r already using frameworks - so research on event listener + publisher. it really solves ur problem ..not only enhancing support to multiple vendors.. it also supports - single - multi thread with less changes.

Related

observer design pattern in rest aplications

I'm trying to learn design patterns, and I have come with the Observer pattern. I think I understand the concept itself, but I don't see when to use it.
I try to explain myself. I work mostly with web applications, so, stateless applications. Normally, the client makes a petition from the browser (for example, update a record). then the operation is completed.
Let us suppose that I want to notify some persons every time a record is updated. It seems to me the perfect scenario for the Observer patter, but when I think of it, it will end something like:
user makes petition of update.
get all the persons that have to be notified.
put all the persons that have to be notified in the observer.
make the update. (that also will make the notification for the observer pattern).
but... doing it this way, I have to iterate all the persons that I want to notify twice!
And because its a stateless application, I have to go and get all the persons than needs to be notified every time!
I don't know if the observer pattern is more useful for other types of applications, but I can only think of this pattern in a static form, I mean, making the Observer static.
I know I'm losing something, it's a common and accepted pattern, everyone accept it as a valid solution for this concrete problem. What I am not understanding?
First, let's straighten out the terminology.
Each person who wants to be notified is an Observer.
Each type of event which can trigger a notification is an Observable.
Each Observer (person) needs to register itself with the server. It sends a request essentially saying, "I'm interested in foo Observables," which in this case would be, "I'm interested in update events." The server maintains mappings of who is interested in which events.
Every time the server makes an update, it iterates over the mapping of update Observers and sends a notification to each of them.
The advantage is that the server and its Observables have no compile-time knowledge of who the Observers are. Observers are free to register (and unregister) themselves at runtime for any event(s) they are interested in.

Why keep stores untouchable from the action creator on Facebook Flux?

I'm reading about the Facebook Flux and I liked the pattern, but I don't understand why we need keep the store untouchable from the action creator. Facebook only says that it's part of "concern separation" and only the store should know how modify itself. Facebook disagrees with store setters like "setAsRead", but doesn't triggering an event on the action creator through the dispatcher that are captured on the store almost the same thing? And calling something like "setAsRead" doesn't exposes how the store are modifying itself.
Some guys say it causes coupling between the store and action creator, but triggering events on the dispatcher causes coupling between the pub/sub, store and action creator.
Keeping the stores untouchable from the action creator creates the need of the "waitFor". Wait For chains doesn't create more implicit coupling between stores? If some action need stores interacting on some given order why doesn't already make this on the action creator?
Do you guys know the cons to adopt a dispatchless approach with Facebook Flux?
If you implement setters in your store, you would completely break the uni-directional data flow principle that is arguably the central principle of the Flux pattern. Nothing would stop your components, or any other code, from directly manipulating the store's state. Now data mutations no longer come from only stores reacting to actions, so you have many "sources of truth".
The uni-directional data flow principle is as follows, very simplified for the purpose of this discussion:
Actions ----> Stores ----> Components
^ |
|___________________________|
waitFor actually does create a coupling between stores, and it leaks into the Dispatcher which has to provide the waitFor function. It's arguably one of the more contended points of the "vanilla" Flux pattern, and for example Reflux implements it differently, without a central dispatcher.

Using Commands, Events or Services

When designing an application's back-end you will often need to abstract the systems that do things from the systems that actually do them.
There are elements of this in the CQRS and PubSub design patterns.
By way of example:
A new user submits a registration form
Your application receives that data and pushes out a message saying “hey i have some new user data, please do something with this”
A listener / handler / service grabs the data and processes it
(please let me know if that makes no sense)
In my applications I would usually:
Fire a new Event that a Listener is set up to process Event::fire('user.new', $data)
Create a new Command with the data, which is bound to a CommandHandler new NewUserCommand($data)
Call a method in a Service and pass in the data UserService::newUser($data)
While these are nearly exactly the same, I am just wondering - how do you go about deciding which one to use when you are creating the architecture of your applications?
Fire a new Event that a Listener is set up to process
Event::fire('user.new', $data)
Event pattern implies that there could be many handlers, subscribing to the same event and those handlers are disconnected form the sender. Also event handlers usually do not return information to the sender (because there can be actually many handlers and there is a confusion about whose information to return).
So, this is not your case.
Create a new Command with the data, which is bound to a CommandHandler
new NewUserCommand($data)
Commands are an extended way to perform some operation. They can be dispatched, pipelined, queued etc. If you don't need all that capabilities, why to complicate things?
Call a method in a Service and pass in the data
UserService::newUser($data)
Well, this is the most suitable thing for your case, isn't it?
While these are nearly exactly the same, I
am just wondering - how do you go about deciding which one to use when
you are creating the architecture of your applications?
Easy. From many solutions choose only those, which:
metaphorically suitable (do not use events, where your logic does not look like an event)
the simplest (do not go too deep into the depths of programming theories and methods. Always choose solution, that lowers your project development complexity)
When to use command over event?
Command: when I have some single isolated action with few dependencies which must be called from different application parts. The closest analogue is some editor command, which is accessible both from toolbar and menu.
Event: when I have several (at least in perspective) dependent actions, which may be called before/after some other action is executed. For example, if you have a number of services, you can use events to perform cache invalidation for them. Service, that changes a particular object emits "IChangedObject" event. Other services subscribe to such events and respond to them invalidating their cache.

Pros and Cons of Listener/Observer approaches to notify Model changes

In any typical iPhone application, there will be model classes that are responsible for data loading/parsing. Upon completion of the data loading/parsing tasks, the affected controllers needed to be notified of the change in the model and update the view accordingly.
There are several listener/observer approaches for this in iPhone application development. What are the pros/cons and reasons for using each of the following approaches?
KVO
NSNotification
Delegate
Any other known approach
In my own experience:
Delegation:
PRO: use only when you have a single object to notify;
PRO: using an explicit protocol you can document clearly your intentions;
CON: can be the source of crashes and memory leaks if wrongly used (tip: don't retain delegates, assign them, and remember to deassign delegates when / if they are released!)
I wrote about memory management problems generated by delegation in this article on my blog:
http://akosma.com/2009/01/28/10-iphone-memory-management-tips/
NSNotification:
PRO: better when you have several objects to notify;
PRO: very flexible, leads to loosely-coupled classes;
CON: notifications are sent synchronously (so make sure your individual notification handlers only do very little)
CON: sometimes hard to document and maintain. Be sure to clearly explain in header docs what each notification means and when it is sent.
KVO:
Similar concerns about NSNotifications;
CON: even more obscure to document. Be sure to add more header docs or architectural tips on your comments to explain who's listening what. I personally wouldn't use KVO for data loading or parsing tasks.
Personally, when dealing with network-enabled apps talking to a remote web service, I use a singleton data loader class (wrapping ASIHTTPRequest and handling all the serialization and deserialization) which pops notifications when something occurs. This way I can have the app delegate handling connection errors on its own (popping up alerts and such if required), and each controller only cares about the responses it wants.
Of course, this approach depends on the application, but this general architecture might be a starting point for your own code.

NSNotificationCenter vs delegation( using protocols )?

What are the pros and cons of each of them?
Where should I use them specifically?
The rule of thumb here is how many clients would like to be notified of an event. If it's mainly one object (e.g. to dismiss a view or to act upon a button clicked, or to react to a failed download) then you should use the delegate model.
If the event you emit may be of an interest to many objects at once (e.g. screen rotated, memory usage, user login/logout), then you should use the NSNotificationCenter.
Their purposes are different:
Notification is used to broadcast messages to possibly several recipients unknown from the sender.
Delegation is used to send messages to a single known recipient acting on behalf of the sender.
Notifications are generally better for notifying the UI of changes the occur on other threads as well. Apple's documentation strongly discourages the use of delegates across threads where possible, both for stability and performance reasons. On the Mac, they suggest using Bindings, but since they don't exist on the iPhone, notifications are probably your next best bet.
Considering the performance is a good idea (delegation better for small number of notified objects, notification centre better for larger number of objects, or is it? run a profiler) but I think a more important factor since you are talking about Objective-C and less likely to be talking about the really high performance parts of your code base, which are likely to be written in C, is reducing compile-time dependencies between modules.
There is nothing to stop you having an array of delegates rather than a single delegate.
I might use NSNotificationCenter only for status of any network stack components I make and any custom device status monitoring interfaces. But for most coupling, not to do with global status of the app, I think it is clearer to use normal interface contracts in Objective-C in most cases and easier to folow for the people coming after you than to use NSNotificationCenter. In fact I have never used NotificationCenter for my own custom events and prefer to use delegates for ease of code comprehension by someone else reading my code.
And finally, of course with notifications to/from the standard API you don't have choice and must use whichever of the two methods Apple proscribe for a given event.
Notifications are better for decoupling UI components. It allows you to plug any view without any modification in your controllers or models. Definitely better for loosely-coupled design.
But for the performance between delegation and notification, you need to think about the frequency of the call.
Delegation might be better for more frequent events, notifications are better for less frequent events but more recipients. It's up to project what to pick.
An option in between those two is using the observer pattern, without NSNotificationCenter. Look at my Objective-C implementation here.