1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95
| #include <iostream>
#include <memory>
#include <string>
class hello_service_base
{
public:
hello_service_base() {}
virtual ~hello_service_base() {}
virtual std::string say_hello() const = 0;
};
class hello_service_impl final : public hello_service_base
{
public:
std::string say_hello() const final {return "Hello";}
};
class world_service_base
{
public:
world_service_base() {}
virtual ~world_service_base() {}
virtual std::string say_world() const = 0;
};
class world_service_impl final : public world_service_base
{
public:
std::string say_world() const final {return "World";}
};
//! Rappel de l'intérêt d'une fabrique :
//! On a une indirection sur la création d'un objet hello_service_base.
//! Un jour, on pourrait changer l'implémentation de create_service()
//! pour retourner un objet d'un autre type que hello_service_impl.
class hello_factory final
{
public:
static hello_factory& instance() {
static hello_factory soleInstance;
return soleInstance;
}
std::unique_ptr<hello_service_base> create_service() const
{
return std::make_unique<hello_service_impl>();
}
private:
~hello_factory() {}
};
class hello_client final
{
public:
hello_client(hello_service_base& h, world_service_base& w) :
m_hello_service(h),
m_world_service(w)
{}
std::string say() const
{
return m_hello_service.say_hello() + " " + m_world_service.say_world() + "!";
}
private:
hello_service_base& m_hello_service;
world_service_base& m_world_service;
};
//! Indirection sur la construction des objets qui dérivent de hello_service_base et de world_service_base.
//! Pour faire une analogie avec l'injection de dépendances dans Spring de Java,
//! la classe présente a le même rôle que le fichier XML qui contient les "beans".
class configuration final
{
public:
static configuration& instance() {
static configuration soleInstance;
return soleInstance;
}
hello_service_base& get_hello_service() {return *m_hello_service;}
world_service_base& get_world_service() {return m_world_service;}
private:
configuration() :
m_hello_service{hello_factory::instance().create_service()},
m_world_service{}
{}
std::unique_ptr<hello_service_base> m_hello_service;
world_service_impl m_world_service;
};
int main()
{
hello_service_base& hello_service = configuration::instance().get_hello_service();
world_service_base& world_service = configuration::instance().get_world_service();
hello_client client{hello_service, world_service};
std::cout << client.say() << std::endl;
} |
Partager