1、GObject接口定义的先决条件
如果要指定接口在实现时需要其他接口的存在,GObject引入了先决条件的概念:可以将一系列先决条件类型与接口相关联。 例如,如果对象A希望实现接口I1,并且如果接口I1有一个先决条件是需要存在接口I2,则A必须实现I1和I2。
上述机制在实践中非常类似于Java接口I1扩展接口I2:
/* Make the ViewerEditableLossy interface require ViewerEditable interface. */
G_DEFINE_INTERFACE (ViewerEditableLossy, viewer_editable_lossy, VIEWER_TYPE_EDITABLE);
在上面的G_DEFINE_INTERFACE调用中,第三个参数定义了前提条件类型。 这是接口或类的GType。 在这种情况下,ViewerEditable界面是ViewerEditableLossy的前提条件。 下面的代码显示了实现如何实现两个接口并注册其实现:
static void
viewer_file_editable_lossy_compress (ViewerEditableLossy *editable)
{
ViewerFile *self = VIEWER_FILE (editable);
g_print ("File implementation of lossy editable interface compress method: %s.\n",
self->filename);
}
static void
viewer_file_editable_lossy_interface_init (ViewerEditableLossyInterface *iface)
{
iface->compress = viewer_file_editable_lossy_compress;
}
static void
viewer_file_editable_save (ViewerEditable *editable,
GError **error)
{
ViewerFile *self = VIEWER_FILE (editable);
g_print ("File implementation of editable interface save method: %s.\n",
self->filename);
}
static void
viewer_file_editable_undo (ViewerEditable *editable,
guint n_steps)
{
ViewerFile *self = VIEWER_FILE (editable);
g_print ("File implementation of editable interface undo method: %s.\n",
self->filename);
}
static void
viewer_file_editable_redo (ViewerEditable *editable,
guint n_steps)
{
ViewerFile *self = VIEWER_FILE (editable);
g_print ("File implementation of editable interface redo method: %s.\n",
self->filename);
}
static void
viewer_file_editable_interface_init (ViewerEditableInterface *iface)
{
iface->save = viewer_file_editable_save;
iface->undo = viewer_file_editable_undo;
iface->redo = viewer_file_editable_redo;
}
static void
viewer_file_class_init (ViewerFileClass *klass)
{
/* Nothing here. */
}
static void
viewer_file_init (ViewerFile *self)
{
/* Instance variable initialisation code. */
}
G_DEFINE_TYPE_WITH_CODE (ViewerFile, viewer_file, G_TYPE_OBJECT,
G_IMPLEMENT_INTERFACE (VIEWER_TYPE_EDITABLE,
viewer_file_editable_interface_init)
G_IMPLEMENT_INTERFACE (VIEWER_TYPE_EDITABLE_LOSSY,
viewer_file_editable_lossy_interface_init))
非常重要的是注意到,将接口实现添加到主对象的顺序不是随机的:调用G_IMPLEMENT_INTERFACE的g_type_add_interface_static必须先调用一个没有其他接口作为先决条件的接口。