C++11之如何实现控制反转

本文通过一个示例解释了C++11中控制反转(IoC)的概念,展示了如何通过依赖注入(DI)降低对象间的耦合性,提高代码的扩展性和灵活性。讨论了Ioc容器的基本实现和类型擦除的几种方法,并鼓励读者深入学习C++的相关高级应用。
摘要由CSDN通过智能技术生成

一个小例子
我们先写一个不使用控制反转的小例子:

#include <iostream>

using namespace std;

struct A{
    virtual void func(){}
    virtual ~A(){}
};

struct B: public A{
    func(){
  cout << "B" << endl;}
};

struct C:public A{
    func(){
  cout << "C" << endl;}
}

class D{
public:
    D(A* a):m_a(a){}

    void func(){m_a->func();}

    ~D(){
        if (m_a != nullptr)
        {
               delete m_a;
               m_a = nullptr;
        }
    }

private:
    A* m_a;
};

int _tmain(int argc, _TCHAR* argv[])
{
    D* active = nullptr;
    if (condtionB)
    {
        active = new D(new B());
    } 
    else
    {
        active = new D(new C());
    }
    delete active;
    return 0;
}

从上面的例子中可以看到D对象和A对象之间的耦合性就产生了。当A对象派生多个子类时,创建D对象时就不得不多加一个条件的判断,这严重影响了代码的扩展性。也违背了“开放-封闭”的原则。耦合性产生的原因在于D对象的创建直接依赖于new外部对象,也叫做“硬编码”,是的二者关系紧耦合,失去了灵活性。一种解决办法是通过工厂模式来创建对象。

struct Factory{
    static A * Create(const string & condition)
    {

        if (conditionB)
        {
            return new B();
        } 
        else
        {
            return new C();
        }
    }
};

int _tmain(int argc, _TCHAR* argv[])
{
    string condition = "B"
    D* active = new A(Factory::Create(condition))
    active->func();
    delete active;
    return 0;
}
  • 2
    点赞
  • 13
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值