我正在努力改进我使用类和对象的策略。
通过一系列特定的类向下传递对象以保持代码组织的最佳方式是什么?
示例:使用ZedGraph对象(注)这可能不是最好的示例,但它将使您理解这个概念。
class Graphhandler
{
private ZedGraphControl ZGC;
private SubGraphController PortionofGraph;
public class GraphHandler(ZedGraphControl _ZGC)
{
ZGC = _ZGC;
initializeGraph();
}
private void initializeGraph()
{
// notice I am putting the ZGC Object into another class
// and likely that ZGC object will go into another class
PortionofGraph = new SubGraphController(ZGC);
}
}
class SubGraphController
{
private ZedGraphControl ZGC;
private DeeperSubGraphController PortionofGraph;
public class SubGraphController(ZedGraphControl _ZGC)
{
ZGC = _ZGC;
initializeSubGraph();
}
private void initializeSubGraph()
{
PortionofGraph = new DeeperSubGraphController(ZGC);
// is there a better way?
}
}有没有更好的方法通过所有这些调用向下传递yop级别的对象来操作数据?
发布于 2012-01-14 07:42:47
通常,答案是将完全形成的依赖项传递到对象中。例如:
public GraphHandler(SubGraphController portionOfGraph) {
this.portionOfGraph = portionOfGraph;
}
public SubGraphController(DeeperSubGraphController portionOfGraph) {
this.portionOfGraph = portionOfGraph;
}
...
var zedGraphControl = new ZedGraphControl();
var deeperSubGraphController = new DeeperSubGraphController(zedGraphControl);
var subGraphController = new SubGraphController(deeperSubGraphController);
var graphHandler = new GraphHandler(subGraphController);而不是直接在子图控制器中构造DeeperSubGraphController。现在,您通常使用依赖注入框架来编排这一切。
(另请参阅:Dependency Injection Myth: Reference Passing)
发布于 2012-01-14 07:38:51
你可以看看Inversion Of Control (通常是缩写的IoC)。
它基本上是一个超级对象,允许您随时随地访问需要的其他对象。
发布于 2012-01-14 07:24:45
在这种情况下,您可以尝试使用继承。
https://stackoverflow.com/questions/8858521
复制相似问题