我正在尝试设计小部件ADT的界面,其中:
我想强制构建一个小部件只是作用域。小部件由Scope(甚至是子级)拥有,因此只有id保存在小部件中(实际的小部件可以由相关的Scope检索)。 用法:
Scope scope;
TextBox& txtBox1 = scope.create<TextBox>();
TextBox& txtBox2 = scope.create<TextBox>("Enter text..");
txtBox1.setText("...");
txtBox1.setParent(label); // label is a widget in this scope. if not, txtBox1 will be replaced into the label's scope.
结构:
class Widget {
string id;
Scope* scope;
protected:
Widget(Scope& _scope)
: id(generateUniqId()), scope(&_scope) {}
public:
...
virtual ~Widget() = default;
const string& getId() const {return id;}
friend class Scope;
};
class TextBox : public Widget {
string text;
protected:
TextBox(Scope& _scope) : Widget(_scope) {}
TextBox(Scope& _scope, string text) : Widget(_scope), text(text) {}
public:
virtual ~TextBox() = default;
const string& getText() const {return text;}
friend class Scope;
};
class Scope {
map<string, unique_ptr<Widget>> widgets;
public:
...
template <class T, class... Args>
T& create(Args&&... args) {
unique_ptr<T> widget(new T(*this, args...));
string id = widget->getId();
widgets.insert(make_pair(id, move(widget)));
return dynamic_cast<T&>(*widgets[id]);
}
};
问题是:
它被认为是一个糟糕的设计?还有其他想法符合我的要求吗?
非常感谢。 ELAD