First commit
[anna.git] / include / anna / dbos / AutoSet.hpp
1 // ANNA - Anna is Not 'N' Anymore
2 //
3 // (c) Copyright 2005-2014 Eduardo Ramos Testillano & Francisco Ruiz Rayo
4 //
5 // https://bitbucket.org/testillano/anna
6 //
7 // Redistribution and use in source and binary forms, with or without
8 // modification, are permitted provided that the following conditions
9 // are met:
10 //
11 //     * Redistributions of source code must retain the above copyright
12 // notice, this list of conditions and the following disclaimer.
13 //     * Redistributions in binary form must reproduce the above
14 // copyright notice, this list of conditions and the following disclaimer
15 // in the documentation and/or other materials provided with the
16 // distribution.
17 //     * Neither the name of Google Inc. nor the names of its
18 // contributors may be used to endorse or promote products derived from
19 // this software without specific prior written permission.
20 //
21 // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
22 // "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
23 // LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
24 // A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
25 // OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
26 // SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
27 // LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
28 // DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
29 // THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
30 // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
31 // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
32 //
33 // Authors: eduardo.ramos.testillano@gmail.com
34 //          cisco.tierra@gmail.com
35
36
37 #ifndef anna_dbos_AutoSet_hpp
38 #define anna_dbos_AutoSet_hpp
39
40 #include <anna/dbos/Set.hpp>
41
42 namespace anna {
43
44 namespace dbos {
45
46
47 /**
48    Facilita el uso de los punteros a objectos obtenidos a partir de los datos guardados en un medio fisico.
49
50    La idea de esta clase es que el constructor y el destructor de esta clase cooperan para reservar y/o
51    liberar correctamente la instancia de T asociada a esta instancia.
52
53    \param T Clase que vamos a gestionar.
54
55    En el siguiente ejemplo podemos ver la forma habitual de trabajar con un objeto persistente tiene
56    el incoveniente de que tenemos que tener en cuenta cada una de las situaciones en las que la
57    referencia obtenida mediante el metodo \em instantiate debe ser liberada.
58
59    \code
60    Server::Set <Server>* servers (NULL);
61    ServerLoader serverLoader;        // ServerLoader hereda de anna::dbos::Loader.
62    Server* server;
63
64    try {
65       serverLoader.setKey (..........); // Establece los parametros de busqueda
66
67       servers = Server::instantiate (serverLoader);
68
69       if (servers->size () == 0) {
70          ....
71          .... Si fuera necesario trataria la condicion de no encontrar ningun registro
72          ....
73       }
74
75       Server::iterator ii, maxii;
76
77       for (ii = servers->begin (), maxii = servers->end (); ii != maxii; ii ++) {
78          server = *ii;
79
80          .... Trataria cada uno de los Server encontrados ....
81       }
82
83       Server::release (servers);
84    }
85    catch (Exception& ex) {
86       Server::release (servers);
87
88       ...
89       ... Si fuera necesario trataria la condificion de error.
90    }
91    \endcode
92
93    Como podemos ver a continuacion el siguiente metodo es mucho mas sencillo y aporta la gran ventaja de que
94    el sistema trabaja por nosotros para liberar correctamente los recursos.
95
96    \code
97    AutoSet <Server> servers;
98    ServerLoader serverLoader;        // ServerLoader hereda de anna::dbos::Loader.
99    Server* server;
100
101    try {
102       serverLoader.setKey (..........); // Establece los parametros de busqueda
103
104       servers = Server::instantiate (serverLoader);
105
106       if (servers->size () == 0) {
107          ....
108          .... Si fuera necesario trataria la condicion de no encontrar ningun registro
109          ....
110       }
111
112       Server::iterator ii, maxii;
113
114       for (ii = servers->begin (), maxii = servers->end (); ii != maxii; ii ++) {
115          server = *ii;
116
117          .... Trataria cada uno de los Server encontrados ....
118       }
119    }
120    catch (Exception& ex) {
121       ...
122       ... Si fuera necesario trataria la condificion de error.
123    }
124    \endcode
125 */
126 template <typename T> class AutoSet {
127 public:
128   /**
129      Constructor.
130      \param t Instancia del objeto asociado a esta instancia.
131      \warning La instancia deberia haber sido obtenida mediate la invocacion a \em T::instantiate de la
132      clase persistente.
133   */
134   explicit AutoSet(Set <T>* t) : a_t(t) {;}
135
136   /**
137      Constructor.
138   */
139   AutoSet() : a_t(NULL) {;}
140
141   /**
142      Destructor. Invoca al metodo \em T::release
143   */
144   ~AutoSet() { if(a_t != NULL) T::release(a_t); }
145
146   /**
147      Operador ->
148      Permite invocar a metodos de la clase T.
149      \return La instancia de la clase T asociada a esta instancia.
150   */
151   Set <T>* operator -> () const throw() { return a_t; }
152
153   /**
154      Operador copia.
155      \return La instancia de la clase T asociada a esta instancia.
156   */
157   Set <T>* operator = (Set<T>* t)
158   throw() {
159     if(a_t == t)
160       return t;
161
162     if(a_t != NULL)
163       T::release(a_t);
164
165     return a_t = t;
166   }
167
168   /**
169      Operador de conversion.
170      \return La instancia de la clase T asociada a esta instancia.
171   */
172   operator Set <T>*() const throw() { return a_t; }
173
174 private:
175   Set <T>* a_t;
176 };
177
178
179 }
180 }
181
182
183
184 #endif
185
186