开发者

"Dumb" Wrapper class

开发者 https://www.devze.com 2023-04-02 10:59 出处:网络
I have a class, say Provider, that exposes its funcationality to the above service layers of the system. It has a pu开发者_C百科blic method, say GetX(). Now, there are two ways to get the X : XML way

I have a class, say Provider, that exposes its funcationality to the above service layers of the system. It has a pu开发者_C百科blic method, say GetX(). Now, there are two ways to get the X : XML way and non-XML way. Two "Library" classes implement these two ways, one for each. Thus, the structure that happens is something as follows :

public class Provider
{
   private XmlLib _xmlLib;
   private NonXmlLib _nonXmlLib;

   public X GetX( // parameters )
   {
      // validate the parameters
      if ( // some condition)
         X = _xmlLib.GetX();
      else
         X = _nonXmlLib.GetX();
      return X;
   }

   // several other such methods
}

internal class XmlLib
{
    public X GetX()
    {
        // Xml way to get X.
    }

    // several such things to get/send in XML way.
}

internal class NonXmlLib
{
    public X GetX()
    {
       // NonXml way to get X.
    }

    // several such methods to get/send thing in non-XML way.
}

So its like, the Provider class becomes a sort of a dumb wrapper, which only validates the arguments, and based on one condition, decides which lib to call. Is this a good implementation? Any better way to implement this?


Let the GetX method be in an interface. from that point on you can have as many classes that you want that implement the interface.

public interface ISomeInterface { X GetX(); }

Now build a class that will implement the factory design pattern (read about it if you do not know it) and let this class accept the condition which will enable it to decide which class that implements the above interface to return.

here's what I said through code:

public class XmlWay : ISomeInterface
{
    public X GetX()
    { 
        //your implementation
    }
}

public class NonXmlWay : ISomeInterface
{
    public X GetX()
    {
        // Another implementation
    }
}

and finally the factory class

public class MyXFactory
{
public static ISomeInterface GetXImplementation(bool someCondition)
{
if (someCondition)
return new XmlWay();
else
return new NonXmlWay();
}

Now see how elegent your code will look:

ISomeInterface xGen = MyXFactory.GetXImplementation(true);
xGen.GetX();

Hope this helps.

0

精彩评论

暂无评论...
验证码 换一张
取 消