Best way to use C ++ interface

I have an interface class similar to:

class IInterface
{
public:

    virtual ~IInterface() {}

    virtual methodA() = 0;

    virtual methodB() = 0;

};

Then I implement the interface:

class AImplementation : public IInterface
{
    // etc... implementation here
}

When I use the interface in an application, it is better to instantiate a specific AImplementation class. For example.

int main()
{
    AImplementation* ai = new AIImplementation();
}

Or it is better to place the factory create function in the interface, as shown below:

class IInterface
{
public:

    virtual ~IInterface() {}

    static std::tr1::shared_ptr<IInterface> create(); // implementation in .cpp
    virtual methodA() = 0;

    virtual methodB() = 0;

};

Then I could use the interface basically like this:

int main()
{
    std::tr1::shared_ptr<IInterface> test(IInterface::create());
}

The first option seems common practice (not to mention his right). However, the second option was obtained from Effective C ++.

+5
source share
7 answers

One of the most common reasons for using an interface is that you can "program against abstraction," rather than a specific implementation.

, , .

, , , Interface/ factory.

, , , / . , , .

, . , , .

+8

, :

int main(int argc, char* argv[])
{
   //...
   boost::shared_ptr<IInterface> test(new AImplementation);
   //...
   return 0;
}

, "create". , "create" , , .

+4

: 1. . 2. .

1 - , std:: tr1:: shared_ptr, , try/catch.

2 .

create() main(), - IInterface:: create(), create, isn , . , "std:: tr1:: shared_ptr test" , create(), , , , , ++.

factory , , AImplementation(), , , - , AImplementation BImplementation CImplementation, , .

+2

"" ?

factory , , , . ( , , ? , , COM.) , , "" .

, , , factory.

, - . factory , , , .

+1

1- . factory , . I.e., IInterface:: create() , .

, create() .

Factory , , , .

Effective ++ ? ( ). .

+1

, . , , , .

0

:

?

, , Java, , . .

0

All Articles