Consider the case of a car.
You can treat Lamborghini like a car.
You can interpret Yugo as a car.
Lamborghini, Lamborghini. ++ , Lamborghini. Lamborghini , dynamic_cast. Lamborghini, dynamic_cast NULL. Yugo Lamborghini Yugo.
Lamborghini , . Lamborghini , Lamborghini-ness. .
!
, , :
B BFactory::makeB(A &a) {
int n=a.getN();
if(n==1){
return new C();
}
}
C B B. B , C, . B , . , new C()
, ,
B * BFactory::makeB(A &a) {
int n=a.getN();
if(n==1){
return new C();
}
}
: make B , A , B.
class B: public A
{
public:
virtual ~B(){}
static B * makeB(A & a)
{
switch(a.getN())
{
case 1:
return new C();
}
return NULL;
}
};
: B -? A ? A ? . - , . .
class B: public A
{
public:
virtual ~B(){}
virtual B* makeB() = 0;
};
B Bs, A, , B, , , - , , - . , - , B .
class C: public B
{
public:
B* makeB()
{
return new C();
}
};
class D: public B
{
public:
B* makeB()
{
return new D();
}
};
: factory
factory. . . , , A. factory , . A, , A factory, A.
BFactory.h:
#ifndef BFACTORY_H_
#define BFACTORY_H_
#include <exception>
class B
{
public:
virtual ~B(){}
virtual std::string whatAmI() = 0;
protected:
};
enum bType
{
gimmie_a_C,
gimmie_a_D,
gimmie_an_E
};
class BadTypeException: public std::exception
{
public:
const char* what() const noexcept
{
return "Dude! WTF?!?";
}
};
B* BFactory(enum bType type);
#endif
. , , , . : gimme_a_C, 1, , , .
enum bType
{
gimmie_a_C,
gimmie_a_D,
gimmie_an_E
};
, (gimmie_an_E), factory - .
class BadTypeException: public std::exception
{
public:
const char* what() const noexcept
{
return "Dude! WTF?!?";
}
};
, factory. C. D. , C D , , enum bType. , - , - B.
BFactory.cpp:
#include "BFactory.h"
class C:public B
{
std::string whatAmI()
{
return "C";
}
};
class D:public B
{
std::string whatAmI()
{
return "D";
}
};
B* BFactory(enum bType type)
{
switch(type)
{
case gimmie_a_C:
return new C();
case gimmie_a_D:
return new C();
default:
throw BadTypeException();
}
}
, , .
, main.cpp:
#include "BFactory.h"
int main()
{
B * temp;
temp = BFactory(gimmie_a_C);
std::cout << temp->whatAmI() << std::endl;
delete temp;
temp = BFactory(gimmie_a_D);
std::cout << temp->whatAmI() << std::endl;
delete temp;
try
{
temp = BFactory(gimmie_an_E);
std::cout << temp->whatAmI() << std::endl;
}
catch(BadTypeException& wtf)
{
std::cerr << wtf.what() << std::endl;
}
}
- A A., , B B.
, , . unique_ptr B .
std::unique_ptr<B> BFactory(enum bType type)
{
switch(type)
{
case gimmie_a_C:
return std::unique_ptr<B>(new C());
case gimmie_a_D:
return std::unique_ptr<B>(new D());
default:
throw BadTypeException();
}
}
main:
int main()
{
std::unique_ptr<B> temp;
temp = BFactory(gimmie_a_C);
std::cout << temp->whatAmI() << std::endl;
temp = BFactory(gimmie_a_D);
std::cout << temp->whatAmI() << std::endl;
}