Factory

Ξ March 28th, 2010 | → 0 Comments |
Programming |, , , , , , |


 

My goal was to read an XML file containing a list of class names, and then instanciate the classes according to that list by caling a simple function inside a for loop.
The Abstract Factory is a very interesting design pattern that provides an encapsulation mechanism to the creation of families of objects. Combining this with the Factory Method it is possible build a factory that, after ‘generator method’ being registered, enables a simple mapping between a string object and an object.

The example shows an abstract Product which implements a given interface. There are two concrete products that derive from the base definition: a BigProduct and a SmallProduct. Then we have the Factory<T> that will be the production line for objects of type T. In the example, with T = Product, we have Factory<Product> that allows to call registration and creation methods, respectivelly:

template <class P>
void Factory<P>::registerProduct(const std::string& key, const Generator& generator)

template <class P>
P* Factory<P>::newProduct(const std::string& key)

The trick is that during registration you must provide the Generator function (also known as Factory Method) that will be used as building method by the factory. In this implementation, the Generator
is defined by the Factory itself but it could be defined anywhere as long as it returns a pointer to an abstract product. The implemented generation is based on default construction:

template <class P> template <class DP> // where P is Product and DP any kind of Derived Product
P* Factory<P>::generate()
{
return new DP();
}

In practice, using the factory is quite simple…

int main (void)
{
typedef Factory<Product> GenericFactory; // Simplifying the factory type…

GenericFactory factory;

// Register products and ‘generation’ methods…
factory.registerProduct(”BigProduct”, GenericFactory::generate<BigProduct>);
factory.registerProduct(”SmallProduct”, GenericFactory::generate<SmallProduct>);

// Calling for product creation
// NOTE: The use of auto pointer ensures that newly allocated object
//       is automatically destroyed as the end of scope
std::auto_ptr<Product> bp(factory.newProduct(”BigProduct”));
std::auto_ptr<Product> sp(factory.newProduct(”SmallProduct”));

bp->doFeature();
sp->doFeature();

return 0;
}

There is one very interesting evolution of this design that I’ve done, to enable runtime class registration. I’ll post on that the next time.



 

Code Snipet of the Day

Ξ February 4th, 2010 | → 0 Comments |
Programming |, , , |

#include <cctype>
#include <string>
#include <algorithm>


std::string s(”hello”);

std::transform(s.begin(), s.end(), s.begin(), ::toupper);

What does this do?

 

Tokens

Ξ January 31st, 2010 | → 0 Comments |
Programming |, , , |


Experiments with tokens and Boost

 

Tic Tac Toe, just for kicks

Ξ January 16th, 2010 | → 0 Comments |
Programming |, , |


Download here, compile and play.

 

delete NULL

Ξ August 19th, 2009 | → 0 Comments |
Programming |, , , , |

This is one of many small reason which makes me prefer C++ to C.

Of course, object programming provide much better encapsulation and abstraction mechanisms than structs and ’simple’ functions or procedures, but today’s tip is not about that. It’s about managing of dynamically allocated memory.

C provides memory block management with functions from the malloc family to allocate memory chunks (for raw management by the programmer) and the infamous free function to release previously allocated memory, while C++ provides a cleaner (at least in my opinion) approach. C++ defines two ’special’ operators:
- operator new allocates a new chunk of memory, which allocated memory with a given initialization behaviour encapsulated in an object. Also, the access to the allocated memory is clear and well defined by the class interface.
- and operator delete to release previously allocated memory.

But why all this talk? Because I learned a new thing this week (or at least it became more present in my mind). In both languages, you can call the release mechanisms (free or delete) using a NULL pointer without having to protect against undefined behaviour. This means that both of the following are correct:

double *p = 0x0
free( p );
double *q = 0x0; 
delete q;

This feature can be used in C++ to provide the following class scheme:

class Base;
class Derived: public Base;
class Actual {
private:
  Base *ptr;
public:
  Actual(): ptr(NULL) {}
  Actual(Base *ptr): ptr(ptr) {}

  virtual ~Actual()
  { delete ptr; }
};
class FirstActual: public Actual {
public:
  FirstActual(): Actual() {}
  virtual ~FirstActual() {}
};
class SecondActual: public Actual {
public:
  SecondActual(): Actual( new Derived() ) {}
  virtual ~SecondActual() {}
};

By observing in detail the example, it’s easy to understand how class Actual stores objects of class Base or any of their derived types, even if the object pointed by ptr is allocated (which is not mandatory) by the classes derived from Actual. For instance, FirstActual doesn’t allocate a new object which means that ptr remains NULL. SecondActual creates a new instance of a Derived object, passes it to the Actual class, and after that no more memory management worries are necessary. The implementation of the class Actual shall be responsible by calling the associated delete (in the case the delete of a Derived object).

 

Exceptional Readings

Ξ June 12th, 2009 | → 0 Comments |
Programming, Skills |, , |

I don’t usual enjoy reading technical books from cover-to-cover, but the other day an acquaintance showed me a couple of interesting books. After skimming just a few pages decided buy a copy, and now I think they are the best C++ books I’ve ever read.

After more than three years of professional C++ programming (on top of a couple more years during the Computer Engineer graduates course), I don’t see myself a C++ beginner and, of course, these books are not for beginners, but I have to say that I still learned a lot by reading the following books.

After reading these books by Herb Sutter [blog] and Scott Meyers, another set of interesting technical readings is already being considered. Stay tuned…

 

To i++ or to ++i…

Ξ April 25th, 2009 | → 0 Comments |
Programming |, , , |

The question is very simple. When writing a for loop, such as the following one

for( int i = 0; i < 10, /* increment i */ )

Between i++ or ++i, which increment operator would you use? Why?

If you choose the answer “It’s the same! Both increment i.“, or if your answer was “I have always used i++, because /* some place ulterior reason here, like ‘I’m programming in c++ and not in ++c’ */“, then your might thing improving your c++ knowledge a little bit. :-)

I just learned it myself, so I’ll share. In fact, it’s so simple it makes me wonder how many of these small details are missed every time my C++ source code lines are incremented. The best increment operator to be used in the pre-increment.

Why? Because it avoids the creation of a temporary variable. Post-increment (i++) has to create a temporary variable to store the return result (that you won’t be using), while incrementing this as expected. Pre-increment simply increments the value of this and returns.

So, systematically using ++i, instead of i++, should improve your runtime performance - even if so slightly.

 

On the nightstand...


    The Art of Agile Development


    Beautiful Architecture


    Modern C++ Design


    Large Scale C++ Software Design

Personal

Friends


Interesting


Shared Readings