将项附加到C中的不透明链表处理程序



我刚开始使用C中的链表,我发现了一些问题,如果我理解得很好的话,在不知道内部结构(字段(的情况下操作链表!

如果有指向链表的指针,是否可以在不知道其内部结构(不透明(的情况下添加/删除链表中的项?

编辑(添加详细信息(。

因此,问题是创建一组函数来操作链表,给定链表上的处理程序作为参数,该参数以以下方式声明:

typedef struct list *handler;

例如,我创建了一个函数来创建一个链表:

handler ListCreate()
{
handler list = (handler)malloc(sizeof(handler));
if(!list)
{
printf("can not allocate memory n");
return NULL;
}
return list;
}

但当谈到附加时,我只是被阻止了,我认为这是不可能的,但也许我错了。

这就是函数的原型:

int ListAppend(handler list, void *item)

我想做一些类似的事情,但我必须自己解决。这个想法是制作一个不透明的对象接口,然后通过使用switch语句进行强制转换来访问实现文件的属性。我这样做是为了遵循依赖反转原理。所有的代码都在一个文件中,以表明它是编译的,但三个注释行//interface、//dependency和//context可以分解为不同的文件,因此您可以尝试依赖文件的不同实现,而无需更改接口文件。

#include <stdlib.h>
#include <stdio.h>
//interface
typedef enum {
DEP1,
DEP2
} Type;
typedef struct Interface{
struct Interface* ptr;
void* data;
int (*getConcreteStuff)(struct Interface*, Type t);
} Interface;
//dependency
typedef struct {
int concreteStuff1;
} Dependency1;
typedef struct {
int concreteStuff2;
} Dependency2;

static int getConcreteStuff(Interface* interface, Type t) {
switch(t){
case DEP1:
return ((Dependency1*) interface->data)->concreteStuff1;
break;
case DEP2:
return ((Dependency2*) interface->data)->concreteStuff2;
break;
}
}
Interface Dependency1_new(Interface* ptr){
Dependency1* d = malloc(sizeof(*d));
d->concreteStuff1 = 1;
struct Interface x = {ptr, d, getConcreteStuff };
return x;
}
Interface Dependency2_new(Interface* ptr){
Dependency2* d = malloc(sizeof(*d));
d->concreteStuff2 = 2;
struct Interface y = {ptr, d, getConcreteStuff };
return y;
}
//context
typedef struct {
Interface i;
} Context;
void Context_doSomething(Context* ctx, Type t){
printf("%dn", ctx->i.getConcreteStuff(&ctx->i, t));
}
int main(){
Context ctx1 = { Dependency1_new(NULL) };
Context_doSomething(&ctx1, DEP1);
Context ctx2 = { Dependency2_new(&ctx1.i) };
Context_doSomething(&ctx2, DEP2);
Context ctx3 = { *ctx2.i.ptr };
Context_doSomething(&ctx3, DEP1);
return 1;
}

最新更新