c ++接口(类)隐藏真实身份(实例化)

时间:2017-12-05 13:24:53

标签: c++ class interface embedded

我想知道是否有人可以解释我如何使用接口。 一般来说,界面应该在层和架构对象之间的每种情况下使用(允许可测试性,清晰的结构/架构,独立地在团队中工作,......)

我还没有理解的是,包含依赖性..我仍然需要实例化对象Test本身,因此需要将它直接包含在上面的层(arch)中。但我想知道最新情况是什么,只能使用界面。

去这儿的方法是什么? 有人有一个具体的例子(示例:HAL :: Timer as Object和HAL:IF_Timer作为中间件/应用程序创建此类对象并使用它的接口?

// =============== IF_Test.hpp =======================

#ifndef IF_Test_hpp
#define IF_Test_hpp

#include <stdio.h>

class I_Test
{
public:
    I_Test() { };
    virtual ~I_Test() { };
    virtual std::string& toString() = 0;
};

#endif /* IF_Test_hpp */


// =============== Test.hpp =========================

#ifndef Test_hpp
#define Test_hpp

#include <stdio.h>
#include "IF_Test.hpp"

class Test : public I_Test
{
    std::string myName;
public:
    Test();
    ~Test();
    std::string& toString();
};

#endif /* Test_hpp */


// =============== Test.cpp =========================

#include <iostream>
#include <cstdio>
#include <string>

#include "Test.hpp"

Test::Test()
: myName("PeterParkerIsBatman")
{
    std::cout << "Test\n";
}

Test::~Test()
{
    std::cout << "!Test\n";
}

std::string& Test::toString()
{
    return myName;
};


// =============== main.cpp =========================

#include <iostream>

#include "IF_Test.hpp"
/** HERE i still need to include the 
concrete class object, which id likte NOT to do 
(Or do i want this and why?) */
#include "Test.hpp" 

int main(int argc, const char * argv[])
{
    I_Test * obj = new(Test);
    obj->toString();

    std::cout << "Hello, World!\n";

    return 0;
}

1 个答案:

答案 0 :(得分:0)

通过引用抽象类成员ITimer,您可以获得正在寻找的SchedulermTimer实现没有任何了解的抽象层。< / p>

// =============== ITimer.h =======================

class ITimer {
    public:
        virtual double time() = 0;
};

// =============== Timer_A.h =======================

//#include ITimer.h

class Timer_A : public ITimer {
    public:
        double time() override {
            /* One way .. */
            return {};
        }
};

// =============== Timer_B.h =======================

//#include ITimer.h

class Timer_B : public ITimer {
    public:
        double time() override {
            /* Another way .. */   
            return {};
        }
};

// =============== Scheduler.h =======================

//#include ITimer.h     <-- No mention of any specific implementation of the ITimer abstract class

class Scheduler{

public:
    Scheduler(ITimer& timer)
    : mTimer(timer)
    {}

    void run (){
        double time = mTimer.time();
        /* etc .. */
    }

    private:
    ITimer& mTimer;
};

// =============== main.cpp =======================

#include Timer_A.h
#include Timer_B.h
#include Manager.h

int main()
{
    Timer_A timerA;
    Timer_B timerB;

    Scheduler schedulerA(timerA);
    Scheduler schedulerB(timerB);
}

您可以拥有尽可能多的图层,其中包含包含实现的文件(Timer_A.hTimer_B.h)的唯一位置是最高级别。

就像你说的那样,这可以让你非常轻松地改变具体的类,并且例如使用gmock可以提供很好的测试能力。