C++ 依赖倒置示例

本文通过具体的C++代码示例,详细解释了设计模式中的依赖倒置原则,展示了如何在`interface.h`、`jacket.h`、`sweater.h`这些接口或类中实现这一原则,以及在`dip.cpp`中如何依赖于抽象而不是具体实现,以提高代码的可维护性和灵活性。
摘要由CSDN通过智能技术生成

interface.h

#include <iostream>
using namespace std;

#ifndef INTERFACE_H__
#define INTERFACE_H__

class IProduct
{
public:
    virtual void print() = 0;
};

class IFactory
{
public: 
    virtual IProduct* create() = 0;

    void Deliver(IProduct *pstProduct)
    {
        if (nullptr == pstProduct)
        {
            cout << "Invalid product." << endl;
        }
        pstProduct->print();
    }
};
#endif 

jacket.h

#include "interface.h"
#ifndef JACKET_H__
#define JACKET_H__

class Jacket:IProduct
{
public:
    virtual void print();
};

class JacketFactory:IFactory
{
public:
    virtual IProduct* create();
};

void Jacket::print()
{
    cout << "This is a jacket." << endl;
}

IProduct* JacketFactory::create()
{
    Jacket* pst = new Jacket();    
    return (IProduct*)pst;
}
#endif 

sweater.h

#include "interface.h"
#ifndef SWEATER_H__
#define SWEATER_H__
class Sweater:IProduct
{
public:
    virtual void print();
};

class SweaterFactory:IFactory
{
public:
    virtual IProduct* create();
};


void Sweater::print()
{
    cout << "This is a sweater." << endl;
}

IProduct* SweaterFactory::create()
{
    Sweater *pst = new Sweater();    
    return (IProduct*)pst;
}
#endif

dip.cpp

#include "jacket.h"
#include "sweater.h"

int main()
{
    cout << "enter" << endl;

    JacketFactory *pstJacketFactory = new JacketFactory();
    if (nullptr == pstJacketFactory)
    {
        cout << "New JacketFactory failed." << endl;
        return -1;
    }

    IProduct* pstJacket = pstJacketFactory->create();
    if (nullptr == pstJacket)
    {
        cout << "Create jacket failed." << endl;
        delete pstJacketFactory;
        pstJacketFactory = nullptr;
        return -1;
    }

    pstJacket->print();
    delete pstJacketFactory;
    pstJacketFactory = nullptr;
    delete pstJacket;
    pstJacket = nullptr;

    cout << "exit" << endl;
    return 0;
}

执行结果

PS E:\workspace\sample\DIP> g++ dip.cpp
PS E:\workspace\sample\DIP> ./a
enter
This is a jacket.
exit
  • 1
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值