“哑巴”包装类
我有一个类,例如 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 类变成了一种愚蠢的包装器,它仅验证参数,并根据一个条件决定调用哪个库。 这是一个好的实施吗?有更好的方法来实现这个吗?
I have a class, say Provider, that exposes its funcationality to the above service layers of the system. It has a public 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?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
让 GetX 方法位于接口中。从那时起,您可以拥有任意多个实现该接口的类。
现在构建一个将实现工厂设计模式的类(如果您不知道,请阅读它)并让该类接受条件,这将使其能够决定返回哪个实现上述接口的类。
这是我通过代码所说的:
最后是工厂类
现在看看您的代码看起来有多优雅:
希望这会有所帮助。
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.
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:
and finally the factory class
Now see how elegent your code will look:
Hope this helps.