Observer Pattern or just create event handling? - c#

I want to create a "modules" layout in my web application so I can easily add more modules of the same type, for example:
As an example, my WebApp handles subscriptions and email campaigns, and I want to create an interface to allow easily coupling multiple API's, MailChimp, CampaignMonitor, iContact, etc...
so I will create an IMailingService interface where I set up the ground rules and all modules will implement it like
public class CampaignMonitorService : IMailingService
So far so good...
How about fire the interface method upon an action on my webapp?
Should I implement the Observer Design Pattern, should I simple create event handlers, or any other hook?
for example, upon a user subscription I would like to fire the AddSubscriber method on the interface
AddSubscriber(string email, string[] args);
some thing as creating a list, unsubscribing, etc, etc...
What would be the best approach to handle such scenario?

Event handlers are how the Observer pattern is normally implemented in .NET. The pattern is a first class citizen of the .NET world, very much like how the Iterator pattern is built in (with foreach and yield return).
If you do want to use the pattern without events/event handlers, you can use the new IObserver<T> and IObservable<T> (introduced in .NET 4.0).

Related

What is the correct way to pass an Rx Observable inside the program?

I have a rather strange question about passing the Observables and subscription inside the app. Most of the examples are showing tightly coupled code, which is not really what one want.
The question is quite general, but I am using WPF with MVVM framework.
Let's say I have something like this:
Right now it is done with events and on every event Classes are filtered by ID and action is taken by the method call on found class.
I am thinking about replacing event with Rx.
Subject is a stream of events (hot) and sending data all the time. Class 1,2, etc are subscribed and act on UI (for example).
Most example like Replacing C# Events are using IDisposable and I will need it in every component.
private IDisposable planeSpottedSubscription;
jetfighter.PlaneSpotted.Where(x => string.Equals(x.Name, “Eurofighter”)).Subscribe(this.OnPlaneSpotted);
But, I can't subscribe to everything from Main, because it doesn't know about all components in UserControls and items are added dynamically (Class3, Class4 of MyType). Subscribing a Facade is not a problem.
So the question sound like:
Should I pass IObservable<JetFighter> to every control (line in ctor) and make a subscription to IDisposable (sounds strange) or can I somehow reuse Observable and just add filters?

What is better -to call empty methods or to use many interfaces

I'm having a few classes that have one base class named Tool.
In form i have one Tool reference that contains one of the instaces of mentioned classes.
When a MouseDown event occurs on the form i call the current Tool Method ex. "CurrentTool.MethodWhenMouseDown()".
Most of Tools are having 3 methods:
MethodWhenMouseDown()
MethodWhenMouseUp()
MethodWhenMouseMove()
But one or two classes are having just:
MethodWhenMouseDown()
Now which is better:
1.To have all three methods in Tool and the the classes that don't need them just call empty methods.
2.To implement interfaces ex. IMouseMoveListener that would be implemented just by the classes that need to act when MouseMove event occurs. This way if MouseMove event occurs we would ask:
if(CurrentTool is MouseMoveListener)
{
(CurrentTool as IMouseMoveListener).MethodWhenMouseMove();
}
Additional information:
The program is like Ms Paint - the tools are Brush,Bucket(the one that don't need MethodWhenMouseMove),LineTool etc.
In my PaintForm i have one reference of abstrac base class Tool that stores instace one of derived class. The thing that fires event is pictureBox.
Have you considered events to which the tools subscribes? – CodesInChaos
I thougth it would be good practice to have a method in form, that would be called after an evet occurs and the method is calling the siutable method of CurrentTool. ex:
void MouseMoveSubscriber(object sender, MouseEventArgs e)
{
CurrentTool.MethodWhenMouseMove(e);
}
I assume subscribing and unsubscribing the method of CurrentTool each time the CurrentTool was changed a bad practice? I also thought about having all tool refereces in Form and the event would be subscribed by each tool and there would be no need of unsubscrinig. The big drawback in my opinion is that each tool needs to check if it is the CurrentTool.
What you think about it? Thanks for help given.
Performance is not an issue (when the user clicks, the overhead of calling an empty function unnecessarily is of no significance), so this is really about coding ease and code clarity/complexity/maintainability.
So I'd keep it as simple as possible.
I would implement a base class with empty implementations, as this is clean and simple. It requires minimal code in a derived class to get the results you need. It also makes sense (If you don't override the click upcall, you are essentially saying "when a mouse is clicked I wish to do nothing about it").
The next option would be to provide events for mouse up/down/click, and have derived classes subscribe to the events if they wish to. Using events is a standard pattern, but it has the drawback that you have to mess around with the ugly subscription and unsubscription calls. The benefit of this is that if you make them public, these events can be handled by anybody, not just derived classes.
I'd avoid using interfaces and casting - to me this feels like a clunky approach - all it really achieves is fragmenting the "empty functions" approach across a number of different types instead of a simple set of 3 virtual methods. And instead of just calling the methods and knowing they will work, you have to do a lot of type casting and checks first - it just seems messy.
edit
Since you've added some more to the question, I've re-read it and another possibility springs to mind: Create a base Tool class that provides the virtual MouseDown handler that all derived classes need to override. All the normal tools would derive form this.
An additional DragTool class could the derived as an intermediate class that adds the MouseMove and MouseUp handlers that are needed for your special couple of dragging tools.
i.e.
ToolBase (abstract MouseDown)
|
+- ClickTool1
+- ClickTool2
+- DragToolBase (abstract MouseMove + MouseUp)
|
+- DragTool1
+- DragTool2
This would meant there would be no empty implementations in any of your tools.
Without knowing your scenario, I would go with a combination of interfaces and base class:
The base class implements all interfaces with empty virtual methods. The base class is a pure convenience construct. If a tool class wants to inherit from the base class but doesn't need the method it doesn't override it.
In the code that consumes the tools you would work soley with the interfaces. Like this other classes are free to directly implement your interfaces. You gain maximum flexibility like this without any sacrifices.
var mouseMoveListener = CurrentTool as IMouseMoveListener;
var mouseDownListener = CurrentTool as IMouseDownListener;
// ...
if(mouseMoveListener != null)
mouseMoveListener.MethodWhenMouseMove();
if(mouseDownListener != null)
mouseDownListener.MethodWhenMouseDown();
Please note: I used as only instead of is in combination with as.
It depends on actual case. But in your specific case (UI events) I think that have base class with empty handlers (virtual methods) is better than a lot of interfaces. Actually all your tools will inherit from some ToolBase. And invocation code will be smaller and simplier without casting to interfaces.

Design decision - Factory vs Observer Pattern

I have the following scenario:
I have a QueueReader class that will be reading messages from a queue. I also have some Senders like EmailSender and SMSSender, that will send these messages to clients using Email or SMS respectively. In the future more Senders can be added.
I can think of two ways of doing this and I am not sure which would be more beneficial.
Factory Pattern:
I can have a SenderManager that will use a SenderFactory to create the appropriate sender and then call its Send() method.
So the QueueReader upon reading a message will call the SenderManager's Send() which will do the following:
IMySender sender = SenderFactory.CreateSender()
sender.Send()
//I have the information to create the proper Dispatcher in the
//factory based upon the message but I have omitted it for brevity.
So, now if I have to add a new sender, I won't have to change the QueueReader or the SenderManager. I will just add the new Sender and modify the SenderFactory.
Observer Pattern
In contrast to the above, I can have the QueueReader class implement an Event for NewMessage. Then have all my Senders subscribe to this event. The Sender will have access to the information that was in the Factory above to know if the message is for them.
The benefit of this would be any new Sender will simply have to subscribe to the event.
Now that I have written all of this down, I think the Observer Pattern is the cleaner approach...
However, if anyone has any insight or suggestion, please do share.
Thanks!
I would use an hybrid approach:
SenderManager (The observer) would listen to the incoming messages and pick the right sender (or ask the SenderFactory to create one if needed). This has 2 benefits:
First, you have control over which sender you pick (You don't need to expose the SenderManager class) avoiding attack of type ManInTheMiddle. This is particularly important if you are going to expose an API for other developers to implement their own senders.
Second, you can implement a sort of Garbage Collector and dispose of the sender that are no longer needed, instead of having multiple senders that are instantiated and monitoring your stream for nothing.
You will need some kind of registration function to register the senders against the SenderManger.
If you use an ObserverPattern, don't forget to implement a default sender (can be a log system) in order to handle the unwanted messages.
Factory pattern will be fine if you want to create instance based on certain criteria.
If you are sure that you will use either SMS or Email sender then you can consider using Dependency Injection as well and let IMySender be resolved on runtime using any DI container. For example, StructureMap.
I am not sure about observer pattern, seems to be a bit complex.

NHibernate Multiple Event Listeners

Is it possible to register multiple event listeners?
We currently register event listeners using .ExposeConfiguration(AddSoftDelete) in which AddSoftDelete is a class registering the listener;
private static void AddSoftDelete(Configuration config)
{
config.SetListener(ListenerType.Delete, new SoftDeleteListener());
}
We have found that we cannot register multiple event listeners of the same type, i.e. we cannot register more than one listener for "ListenerType.Delete".
Is it possible to register new listeners without overriding any existing ones?
Solved...
Have managed to register multiple listeners using the following code;
config.EventListeners.PreUpdateEventListeners = new IPreUpdateEventListener[]
{
new Listener1(),
new Listener2()
};
Repeat for each ListenerType.
The listeners are not actually listeners, they are implementors. There could only be one implementation of an "event".
You could implement a listener where you could plug in several implementations. For instance an implementation for different entity types. You could pass the "event" to each implementation until one of them handles it (eg. when the ISoftDeletable interface is implemented, the SoftDeleteImplementor is handling it). You need to care about competing implementors (more the one could be handling it, the order matters in which you call them).
Why is there a need to register more than one ListenerType.Delete?
If you've got multiple event listeners on one type, there will be some performance issues on your application. If you want to handle different entities with this listener, so do it in your SoftDeleteListener class.
I do something similar in my code. There should be an AppendListeners(ListenerType type, object[] listeners) method on the NHibernate.Cfg.Configuration object.
There's also a SetListeners method which I assume replaces the listener list instead of adding on to it.

Auto wire event handlers with StructureMap?

Say I have an event defined in an interface.
I then have many classes that implement that interface.
The creation of these classes is managed by StructureMap.
Now say I have one delegate that I want to use as the event handler for ALL of these newly created instances.
Is there a way to tell StructureMap to append an event handler to objects it creates?
(NOTE: My current solution is to create a Notifier class and pass that in through the constructor, which gets the job done, but I'm curious if I can eliminate the middleman.)
If you take a look at http://structuremap.sourceforge.net/Interception.htm there is an explanation to EnrichWith()
Add the the event handler and return the original object and you should have what you want.

Categories