我在为我的游戏设计GUI时遇到了问题。到目前为止,我得出的结论是,复合模式将允许我对所有UIComponents进行相同的处理,不管其中一个是UIButton,另一个是UIMenu。下面是UIComponent接口:
class UIComponent {
virtual void Init() = 0;
virtual void Draw() = 0;
}我的每个实现类(UIFrame、UIButton、UITextBox、UIMenu、.)现在都可以相互工作了。本设计中的复合类是UIMenu类,因为它是A UIComponent,有A UIComponent。
class UIMenu : public UIComponent {
private:
vector<UIComponent*> children_;
public:
virtual void Init() {
// Initialize any data
};
virtual void Draw() {
// Delegate drawing to each child
for each(UIComponent* component in children_) {
component->Draw();
}
};
void AddComponent(UIComponent* child) {...};
void RemoveComponent(UIComponent* child) {...};
}因为我想支持所有UIComponents,之间的拖放功能,所以每个组件都需要位置、维度、缩放、父级和层(ComponentData).。要做到这一点,我需要将它们分别添加到每个实现类中,这在我看来是错误的。
class UIFrame : public UIComponent {
private:
string imgID_;
int layer_;
double relX_, relY_;
double width_, height_;
double scaleX_, scaleY_;
UIComponent* parent_;
public:
virtual void Init() {...}
virtual void Draw() {...}
...
};这不是已经打破了复合模式,因为我现在已经通过聚合使每个组件实现为一个复合?如果我希望我的UIButtons具有相同的定位、转换和缩放功能,我需要从UIFrame继承或者将数据成员复制到UIButton中。
是否有更好的方法来创建UIComponent接口的实现?例如,与UIButton、UITextBox、UILabel等不同,我们可以让UIFrame作为所有需要移动功能的组件的基类。现在,像UIButton这样的组件将是UIFrame的子组件,以便重用ComponentData。
在UIComponent接口中放置与定位、转换和缩放相关的方法更好吗?这将强制每个组件都知道如何在屏幕上操作自己。然而,我仍然有一个问题,“我把ComponentData (位置,尺寸,比例)放在哪里?”
我非常喜欢复合模式的想法,以及原子化地处理树结构的叶子和分支节点的能力。它还允许我使用Decorator模式来创建UIMenu对象的多次迭代,这样我就可以拥有一个InventoryMenu、CharacterInfoMenu、OptionsMenu等等,所有这些都可以通过更改每个菜单中的UIComponents来实现。
发布于 2014-04-15 20:16:18
您可以使用支持拖放的数据项和方法创建一个超类UIDraggable,并且每个可拖放元素都可以继承它。UIDraggable可以继承UIComponent。
https://stackoverflow.com/questions/23090811
复制相似问题