I have a scenario I am coding, where I feel the Adaptor Pattern would be useful. I have a service that has multiple possible providers I want to switch when I like, so as long as each "Adapter" follows the same rules (interface) the underlying code is hidden from the caller.
With this in mind, I've been looking at a number of examples. This code snippet is taken from this stack overflow example:
Interface ITarget
{
public void GetData();
}
//Decision to use MSDAO
class AdaptorMS : ITarget
{
public void GetData()
{
MSDAO objmsdao = new MSDAO();
objmsdao.GetDataMethod();
}
}
// calling code
class Client
{
static void Main(string[] args)
{
ITarget objAdaptor = new AdaptorMS();
object dummyObject = objAdaptor.GetData();
}
}
Then we decide to create a new adaptor that we will change to:
//After a month, the decision to use OracaleDAO was taken, so create a new adapter
class AdaptorOracle: ITarget
{
public void GetData()
{
OracleDAO objrracledao = new OracleDAO();
objoracledao.GetSomeData();
}
}
// Calling code
class Client
{
static void Main(string[] args)
{
ITarget objAdaptor = new AdaptorOracle();
object dummyObject = objAdaptor.GetData();
}
}
I've also seen this example:
public class AdaptorA : ITarget
{
private TargetA A { get; set; }
public AdaptorA( TargetA a )
{
this.A = a;
}
public void GetData() {
return this.A.SomeGetDataCall();
}
}
public class AdaptorB : ITarget
{
private TargetB B { get; set; }
public AdaptorB( TargetB a )
{
this.B = a;
}
public void GetData() {
this.B.MakeDataCall();
}
}
We have two new adaptors but what I don't understand about the above example, is the fact the Adaptor class takes a parameter for the underlying system it will call (TargetA or TargetB). What's the difference in the two examples? I get the first example, hiding all implementation from the calling code (instance of OracleDAO is inside the adaptor), but not the second. Is there a fundamental difference or have I misunderstood the pattern?
Thanks in advance for any advice!
Aucun commentaire:
Enregistrer un commentaire