【发布时间】:2015-06-22 13:25:36
【问题描述】:
访问/修改深度嵌套对象的正确方法是什么?
看下面的例子。
public class DrawBoard
{
MouseTracker mouseTracker_;
DrawTool* drawTool_;
void init()
{
mouseTracker_ = new MouseTracker(area);
mouseTracker_.setTool(new PenTool());
}
void OnMouseEvent(MouseEvent e)
{
mouseTracker_->handleMouseEvent(e);
}
//UI Button setting the tool
void OnPenButtonClick()
{
mouseTracker_.SetTool(new PenTool());
}
void OnLineButtonClick()
{
mouseTracker_.SetTool(new LineTool());
}
void OnCircleButtonClick()
{
mouseTracker_.SetTool(new CircleTool());
}
//UI slide bar changing the color
void OnColorSlideBarChange(int color)
{
//What should I do here?
//Chained getters : mouseTracker.getDrawTool().setColor(color);
//Delegate Method: mouseTracker.setColor(color);
//Shared Object: Store the current tool in "drawTool_" - drawTool_ = new PenTool();
// mouseTracker_.SetTool(drawTool_);
//and just call drawTool_.setColor(color) on color change
}
}
public class MouseTracker;
{
DrawTool* tool_;
void handleMouseEvent(MouseEvent e)
{
Shape s = tool->process(e)
s.Draw();
}
void SetTool(DrawTool tool)
{
tool_ = tool;
}
}
public class DrawTool
{
int color_;
Shape* process(MouseEvent e)
{
/** process e **/
Shape s = new Pen\Line\Circle(color_);
return s;
}
void SetColor(int color)
{
color_ = color;
}
} PenTool, LineTool, CircleTool;
public class Shape
{
void Draw() { Implementation };
} Pen, Line, Circle;
DrawBoard 是一个 UI 类。
MouseTracker 是一个用于处理事件并采取相应措施的类。
DrawTool 是用于创建Shapes 的类。 PenTool、LineTool、CircleTool 是它的子类。
Shape 是用于绘制的类。 Pen、Line、Circle 是它的子类。
现在从 DrawBoard 开始,我正在尝试根据 UI 事件(在本例中为 OnColorSlideBarChange)更改 drawTool 的颜色。我只能看到 3 种方法。
链式吸气剂
mouseTracker.getDrawTool().setColor(color);
但上面的例子是一个简化的例子。如果两者之间有更多的依赖关系。它可能会很快成长为
mouseTracker.getA().getB().getC().getDrawTool().setColor(color); 我必须为每个类编写一个 getter 方法。
委托方法
mouseTracker.setColor(color);
与上面类似,只是我在一个委托方法中隐藏了细节。
共享对象
将当前工具存储在DrawBoard 类中的“drawTool_”中,并在每次工具更改时更新它
drawTool_ = new PenTool();
mouseTracker_.SetTool(drawTool_);
改变颜色只是
drawTool_.setColor(color)
但我这样做似乎打破了封装。
有没有更好的方法来处理这种情况?
【问题讨论】:
标签: design-patterns dependency-injection dependencies