“哑巴”包装课

时间:2011-09-06 07:59:49

标签: oop class-design wrapper

我有一个类,比如Provider,它将其功能暴露给系统的上述服务层。它有一个公共方法,比如GetX()。现在,有两种方法可以获得X:XML方式和非XML方式。两个“库”类实现这两种方式,每种方式一个。 因此,发生的结构如下:

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.
}

就像它一样,Provider类变成了一种愚蠢的包装器,它只验证参数,并根据一个条件决定调用哪个lib。 这是一个很好的实现吗?有没有更好的方法来实现这个?

1 个答案:

答案 0 :(得分:1)

让GetX方法在一个接口中。从那时起,您可以拥有所需的实现接口的类。

public interface ISomeInterface { X GetX(); }

现在构建一个将实现工厂设计模式的类(如果你不知道它,请阅读它)并让这个类接受使它能够决定实现上述接口的类返回的条件。 p>

这是我通过代码说的话:

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

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

最后是工厂类

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

现在看看你的代码看起来有多优雅:

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

希望这有帮助。