Реализации на С++
Factory method
Общая реализация на языке С++
class Car
{
public:
virtual ~Car() = default;
virtual void drive() = 0;
};
class Sedan : public Car
{
public:
Sedan()
{
cout << "Sedan constructor called" << endl;
}
~Sedan() override
{
cout << "Sedan destructor called" << endl;
}
void drive() override
{
cout << "Driving sedan" << endl;
}
};
class SUV : public Car
{
public:
SUV()
{
cout << "Calling the SUV constructor;" << endl;
}
~SUV() override
{
cout << "Calling the SUV destructor;" << endl;
}
void drive() override
{
cout << "Driving SUV;" << endl;
}
};
class VehicleSolution
{
public:
using CreateCarMaker = unique_ptr<CarCreator>(&)();
using CallBackMap = map<size_t, CreateCarCreator>;
public:
VehicleSolution() = default;
VehicleSolution(initializer_list<pair<size_t, CreateCarCreator>> list);
bool registrate(size_t id, CreateCarCreator createfun);
bool check(size_t id)
{
return callbacks.erase(id) == 1;
}
unique_ptr<CarCreator> create(size_t id);
private:
CallBackMap callbacks;
};
# include <iostream>
# include <initializer_list>
# include <memory>
# include <map>
# include <exception>
using namespace std;
int main()
{
try
{
shared_ptr<VehicleSolution> solution
= make_solution({ {1, CarCreatorMaker::createCarCreator<Sedan>} });
if (!solution->registrate(2, CarCreatorMaker::createCarCreator<SUV>))
{
throw runtime_error("Error registration!");
}
shared_ptr<CarCreator> cr(solution->create(2));
User{}.use(cr);
}
catch (runtime_error& err)
{
cout << err.what() << endl;
}
}
Last updated
Was this helpful?