" IOC容器"只是维护依赖关系?

时间:2017-12-14 03:40:57

标签: javascript c spring design-patterns ioc-container

根据wiki

  

依赖是可以使用的对象(作为服务)。

Image processing application是OOP范例样式C语法,它解决了4个角色,如下所示。

1)interface(handlers.h

typedef struct {
    int (*canHandle) (char *);
    int (*drawImage)(char *);
    int (*savefile)(char *);
}imageHandler;

2)取一个依赖关系(gifhandler.c

imageHandler gifhandler = {
    gif_canHandle,
    gif_drawImage,
    gif_savefile
};

3)依赖容器(由config.c处理)

//gifhandler.c - dependency 
int _init(){
    printf(" registering gifhandler \n");
    reg_handler(&gifhandler);
    return 0;
}

//config.c
imageHandler *imagehandlers[10];
int reg_handler(imageHandler *ih){
// we need to perform checks here.
    imagehandlers[libs] = ih;
    libs++;
    return TRUE;
}
// config.c
int init_handlers(){
    .....
    soptr = dlopen(so_name,RTLD_NOW);
    ....
}

4)客户 - 服务定位器(UI.C

// UI.C
switch(choice){
        case 1:
            vdrawImage(filename);   
            break;
        case 2:
            vsavefile(filename);
            break;
}
// viml.c
int vdrawImage(char *filename){
    ...
    handleno = find_handler(filename);
    ...
    ih=imagehandlers[handleno];
    ih->drawImage(filename);    
    return FALSE;       
}
// viml.c
int vsavefile(char *newfilename ){
    ...
    handleno = find_handler(newfilename);
    ...
    ih=imagehandlers[handleno];
    ih->savefile(newfilename); 
}

1)要在依赖关系容器中添加新的依赖关系(libxyzhandl.so.1),只需要在config.txt 可配置中添加新条目,如下所示,

  

config.txt

     

./libgifhandl.so.1

     

./libtiffhandl.so.1

2)./libxyzhandl.so.1提供的新服务将包含在依赖容器中,无需重新编译

3)完整申请的测试不是必需的,但libxyzhandl.so的源代码除外。

因此,如果config.txt变为空,则应用程序不会执行任何操作,除了对任何输入(图像文件)说We cannot handle this kind of files,显示为here

以下是呼叫流程的可视化,

enter image description here

问题:

1)依赖容器 IOC容器不同吗?

2) Spring IOC容器是否提供了比维护依赖项更多的功能?

1 个答案:

答案 0 :(得分:1)

这些基本上是一回事。人们倾向于互换使用它们。您可以找到一个很好的解释herehere 您已经展示的实现允许简单的运行时注入依赖项,但所谓的 IoC容器就像Spring上下文一样没有什么不同。