I have an email component that I am integrating into my application, looking for some tips on how should build a wrapper around it so I can swap it out with another 3rd party component if needed.
My approach right now is it:
- build an interface will the functionality I need.
- create a class that implements the interface, using my 3rd party component inside this class.
any usage of this component will be via the interface so like:
IPop3 pop3 = new AcmeIncePop3Wrapper(); pop3.connect();
and inside AcmeIncePop3Wrapper will be:
public void connect()
{
AcmeIncePop3 pop = new AcmeIncePop3();
pop.connect();
开发者_如何学编程 }
Is that a good approach?
I could probably add another abstraction by using ninject so I could swap out implementations, but really this seems to be all I need as i don't expect to be changing 3rd party assemblies every day, just don't want to make things so tightly coupled.
I think you have a good implementation. Basically your interface says "This is how I want to deal with email" and the third party components may do things differently, but if you build your wrapper classes based on your interface you should be able to work any third party component into that interface.
The only thing you may want to watch out for is where you are newing up the concrete classes. You could consider using a factory or something if you're newing it up alot - if not it may not be a big deal. I'm just thinking that if you create new AcmeIncePop3() all over the place then it's still rather tightly coupled to that concrete class.
I'd say your implementation is fine, that's exactly the sort of thing I'd do to wrap something.
You're on the right lines.
Simply using an interface wouldn't solve it, as you can't add the interface to the definition to the class you need if it is located in a 3rd party assembly. Instead, do one of two things:
create a whole new class with methods common to all the different assemblies you know of, and handle each different assembly that can exist (additional logic might be needed here to handle major differences).
create an interface with common methods etc., then create a new class that inherits from the 3rd party class and implements the interface. Do this for each class in new assemblies that you need to use.
The problem with option 2 is that you can't extend a sealed class
, which I would expect a third party to do.
I recommend option 1.
精彩评论