Discussing the nuts and bolts of software development

Wednesday, May 14, 2008

 

Java programmer living in a C++ world

Being a long time Java programmer, I've become familiar and fond of many of the features provided by the language. Reflection and runtime type identification add an extra level of power to any programming language. When I returned to C++ development, I found it necessary to fill the void I had grow accustomed to in the Java world.

Inversion of control in C++

Inversion of control is a powerful design pattern (and/or philosophy) that allows for loosely coupled and highly reusable objects. The main principle is that an owner object is responsible for supplying all the needed information and resources to any object contained within. This includes configuration, initialization, logging, thread pools, databases and any other conceivable resource.

When dealing with inversion of control, it's often desirable to test if a particular object implements a specific interface. An object may implement the Configurable interface, but not the Loggable interface. This is easy enough to do in Java using the "instanceof" keyword or via reflection. In C++, you must do things a bit different:


class Configuration;

class Configurable
{
public:
virtual void configure(const Configuration &configuration) = 0;
template<class>
static bool tryConfigure(T *obj,
const Configuration &configuration)
{
Configurable *configurable = dynamic_cast<Configurable>(obj);
if (configurable)
{
configurable->configure(configuration);
return true;
}
return false;
}
};


In this case, a owner object can attempt to configure a child object simply by calling the static method tryConfigure. If it the supplied object is of the wrong type, it will simply return false.


Configuration config;
Configurable::tryConfigure( &ownedObjectA, config );


The same can be applied for initializing and de-initializing objects. Note that the static testing method is templated so the object type is not lost when passed in.


class Initializable
{
public:
virtual bool initialize(void) = 0;
virtual bool deinitialize(void) = 0;

template<class>
static bool tryInit(T *obj)
{
Initializable *init = dynamic_cast<Initializable>(obj);
if (init)
{
return init->initialize();
}
return false;
}

template<class>
static bool tryDeinit(T *obj)
{
Initializable *init = dynamic_cast<Initializable>(obj);
if (init)
{
return init->deinitialize();
}
return false;
}
};

Singletons in C++

Singleton is the most basic of all patterns, but extremely valuable. Care must be taken not to overuse singletons, but in the right place, they are a design gem. In C++ there is a simple template way to reduce the coding overhead of returning a static instance, and also unify the method names to get the instance.

template <class> class Singleton
{
public:
// Virtual destructor
virtual ~Singleton() {}

// Get instance as pointer
inline static Target *ptr(void) { return &(ref()); }

// Get instance as reference
inline static Target &ref(void) {
static Target theInstance;
return theInstance;
}
protected:
Singleton(void) {} // Default constructor
};

To inherit a singleton object, one extra step must be taken so that the inherited constructor is called. That is to add the templated version of singleton as a friend to the class.


class MySingletonClass : public Singleton<MySingletonClass>
{
friend class Singleton<MySingletonClass>;
};

NOTE: Some compiler optimizations of a static inline method might cause undesirable effects, such as multiple instances of a singleton. You may need to twiddle optimization flags.


Factories in C++

Factories are responsible for creating objects of a specific interface type. For example, you could have a LoggerFactory that is able to create a PlainTextLogger, an XMLLogger and a SocketLogger. Unlike Java, in C++ it is difficult to dynamically create an instance of a class based on its name alone. By combining a Prototype pattern and a C macro, it is possible to register a class by name, and instantiate it later by name. This is somewhat analogous of querying an interface in Microsoft COM.


#include <string>
#include <map>

class Prototype
{
public:
virtual bool createInstance(void **instance) = 0;
};

template<class>
class PrototypeTemplate : public Prototype
{
public:
virtual bool createInstance(void **instance) {
if (instance)
{
*instance = new T();
return true;
}
return false;
}
};

#define xstr(s) #s
#define PROTOTYPE(x) xstr(x), new PrototypeTemplate<x>()


template<class>
class Factory
{
public:

bool queryPrototype(const std::string &name, T **instance)
{
if (name.empty() || (!instance))
return false;

if (m_registeredPrototypes.find(name) != m_registeredPrototypes.end())
{
return m_registeredPrototypes[name]->createInstance(
(void **) instance);
}
return false;
}

virtual ~Factory(void)
{
// Release the prototypes
for (std::map<std::string,>::iterator it =
m_registeredPrototypes.begin();
it != m_registeredPrototypes.end(); it++)
delete it->second;
}
protected:

/* Protected by default. Can re-expose as public if you want
outside code able to register new prototypes */
void registerPrototype(const std::string &name, Prototype *prototype)
{
m_registeredPrototypes[name] = prototype;
}

std::map<std::string,> m_registeredPrototypes;
};

A typical implementation may look like this:


#include "Factory.h"
#include "Singleton.h"

#include "Logger.h"
#include "PlainTextLogger.h"
#include "XMLLogger.h"
#include "SocketLogger.h"

namespace Protected {
// This namespace is really just an attempt to hide the base type, since it must
// first be templated as a factory, and then as a singleton.

class LoggerFactory : public Factory<Logger>
{
public:
LoggerFactory(void)
{
registerPrototype( PROTOTYPE( PlainTextLogger ) );
registerPrototype( PROTOTYPE( XMLLogger ) );
registerPrototype( PROTOTYPE( SocketLogger ) );
}
};
}


class LoggerFactory : public Protected::LoggerFactory,
public Singleton<LoggerFactory>
{
friend class Singleton<LoggerFactory>
};

We can now create a logger dynamically by specifying the name of the class as a string. In this manner, the logger could be determined at runtime from a configuration item. It would also be possible to register prototypes at runtime via DLL or shared objects.


Configuration config;
Logger *myLogger;
std::string loggerTypeName;

if( !config.getValue("logger", loggerTypeName ) ||
loggerTypeName.empty() ||
!LoggerFactory::ref().queryPrototype( loggerTypeName, &myLogger ) )
{
// Not found, default to known existing logger
loggerTypeName = "PlainTextLogger";
LoggerFactory::ref().queryPrototype( loggerTypeName, &myLogger );
}
Configurable::tryConfigure( myLogger, config.getSubConfiguration( loggerTypeName ) );
Initializable::tryInit( myLogger );


Comments:
I have read your blog its very attractive and impressive. I like it your blog.

Java Training in Chennai Core Java Training in Chennai Core Java Training in Chennai

Java Online Training Java Online Training Core Java 8 Training in Chennai Core java 8 online training JavaEE Training in Chennai Java EE Training in Chennai
 
Java Online Training Java Online Training Java Online Training Java Online Training Java Online Training Java Online Training

Hibernate Online Training Hibernate Online Training Spring Online Training Spring Online Training Spring Batch Training Online Spring Batch Training Online
 
Java Training Institutes Java Training Institutes Java EE Training in Chennai Java EE Training in Chennai Java Spring Hibernate Training Institutes in Chennai J2EE Training Institutes in Chennai J2EE Training Institutes in Chennai Core Java Training Institutes in Chennai Core Java Training Institutes in Chennai

 
Simply superb about this blog. Really a great job. Good information for the freshers.
Seeking for this kind of information and got it thank you for the post.
best institute for java
best java training
java programming certification course
best java certification
best java training
best java training institutes
 
Hey Nice Blog!! Thanks For Sharing!!!Wonderful blog & good post.Its really helpful for me, waiting for a more new post. Keep Blogging!
SEO company in coimbatore
Digital Marketing Company in Coimbatore
web design in coimbatore

 
Do you want to get some interesting persuasive essay topics? Here you can find more info about it
 
Interesting information and attractive.This blog is really rocking... Yes, the post is very interesting and I really like it.I never seen articles like this. I meant it's so knowledgeable, informative, and good looking site. I appreciate your hard work. Good job.
Kindly visit us @
Sathya Online Shopping
Online AC Price | Air Conditioner Online | AC Offers Online | AC Online Shopping
Inverter AC | Best Inverter AC | Inverter Split AC
Buy Split AC Online | Best Split AC | Split AC Online
LED TV Sale | Buy LED TV Online | Smart LED TV | LED TV Price
Laptop Price | Laptops for Sale | Buy Laptop | Buy Laptop Online
Full HD TV Price | LED HD TV Price
Buy Ultra HD TV | Buy Ultra HD TV Online
Buy Mobile Online | Buy Smartphone Online in India

 
The article is very interesting and very understood to be read, may be useful for the people. I wanted to thank you for this great read!! I definitely enjoyed every little bit of it. I have to bookmarked to check out new stuff on your post. Thanks for sharing the information keep updating, looking forward for more posts..
Kindly visit us @
Madurai Travels
Best Travels in Madurai
Cabs in Madurai
Tours and Travels in Madurai


 
Excellent Blog. I really want to admire the quality of this post. I like the way of your presentation of ideas, views and valuable content. No doubt you are doing great work. I’ll be waiting for your next post. Thanks .Keep it up!
Kindly visit us @
Luxury Packaging Box
Wallet Box
Perfume Box Manufacturer
Candle Packaging Boxes
Luxury Leather Box
Luxury Clothes Box
Luxury Cosmetics Box
Shoe Box Manufacturer
Luxury Watch Box

 
Wow, what an awesome spot to spend hours and hours! It's beautiful and I'm also surprised that you had it all to yourselves!
Kindly visit us @
Best HIV Treatment in India
Top HIV Hospital in India
HIV AIDS Treatment in Mumbai
HIV Specialist in Bangalore
HIV Positive Treatment in India
Medicine for AIDS in India


 
Nice blog, it's so knowledgeable, informative, and good looking site. I appreciate your hard work. Good job. Thank you for this wonderful sharing with us. Keep Sharing. Kindly visit us @ 100% Job Placement | Best Colleges for Computer Engineering
Biomedical Engineering Colleges in Coimbatore | Best Biotechnology Colleges in Tamilnadu | Biotechnology Colleges in Coimbatore
Biotechnology Courses in Coimbatore | Best MCA Colleges in Tamilnadu | Best MBA Colleges in Coimbatore
Engineering Courses in Tamilnadu | Engg Colleges in Coimbatore


 
Great article and it is very inspiring to me. I glad to satisfied with your good job. You put the effort is very superb and I appreciate for your unique information. Keep it up.
Pega Training in Chennai
Pega Course in Chennai
Excel Training in Chennai
Corporate Training in Chennai
Embedded System Course Chennai
Linux Training in Chennai
Spark Training in Chennai
Tableau Training in Chennai
Pega Training in Tambaram
Pega Training in Porur
 
A very interesting blog

 
A very interesting blog....
 
very keen programming. visit us to know more about android app development
 
Hello Admin!

Thanks for the post. It was very interesting and meaningful. I really appreciate it! Keep updating stuffs like this. If you are looking for the Advertising Agency in Chennai | Printing in Chennai , Visit Inoventic Creative Agency Today..

 
Nice post...Thanks for sharing...
Software Testing Course in Bangalore

 
Great Article… I love to read your articles because your writing style is too good, its is very very helpful for all of us and I never get bored while reading your article because, they are becomes a more and more interesting from the starting lines until the end. Software Testing Training in Chennai | Software Testing Training in Anna Nagar | Software Testing Training in OMR | Software Testing Training in Porur | Software Testing Training in Tambaram | Software Testing Training in Velachery

 
Great article!I learn a lot from this article,this is my website ,i am looking forward you to visiting it. http://tjproducts.com.sg/
 
Very interesting blog. Many blogs I see these days do not really provide anything that attracts others, but believe me the way you interact is literally awesome.You can also check my articles as well.

Home Garden Blogs

Thank you..
 
Very interesting blog. Many blogs I see these days do not really provide anything that attracts others, but believe me the way you interact is literally awesome.You can also check my articles as well.

Security Guard License
Ontario Security License
Security License Ontario
Security License

Thank you..

 
Excellent blog with top quality information and enjoyed reading waiting for next blog thank you.
Data Analytics Course Online 360DigiTMG
 
Great article with top quality information, found valuable and knowledgeable thanks for sharing waiting for next blog update.
Ethical Hacking Course in Bangalore
 
Awesome blog with excellent information, I really enjoyed it waiting for next blog update thank you.
Data Science Training in Hyderabad
 
I will very much appreciate the writer's choice for choosing this excellent article suitable for my topic. Here is a detailed description of the topic of the article that helped me the most. PMP Certification in Hyderabad
 
Very interesting blog. Many blogs I see these days do not really provide anything that attracts others, but believe me the way you interact is literally awesome.You can also check my articles as well.

Rowe Rowe
Rowe Rowe Interval

Thank you..
 
Artificial Intelligence and Machine Learning in Data Science technology are excelling in solving highly complex data-rich problems. To think beyond the human brain and maintain the balance with the information that’s evolved, disrupted, and being employed the sectors altogether, data scientists foster new methodologies.
Data Science Course in Hyderabad
Data Science Course Training in Hyderabad
 
Nice Information Your first-class knowledge of this great job can become a suitable foundation for these people. I did some research on the subject and found that almost everyone will agree with your blog.
Cyber Security Course in Bangalore
 
Writing in style and getting good compliments on the article is hard enough, to be honest, but you did it so calmly and with such a great feeling and got the job done. This item is owned with style and I give it a nice compliment. Better!
Cyber Security Training in Bangalore
 
Arga detectives es una agencia de investigación privada con gran experiencia. contacta con los mejores detectives privados en Madrid. Solicita presupuesto gratuito de detectives privados en España al mejor precio.

Detectives privados
private investigators madrid

Thank you..
 
It is late to find this act. At least one should be familiar with the fact that such events exist. I agree with your blog and will come back to inspect it further in the future, so keep your performance going.

Business Analytics Course in Bangalore
 
I wanted to leave a little comment to support you and wish you the best of luck. We wish you the best of luck in all of your blogging endeavors.

Data Analytics Course in Bangalore
 
Very interesting blog. Many blogs I see these days do not really provide anything that attracts others, but believe me the way you interact is literally awesome.You can also check my articles as well.

Rental Properties & Dubai Real Estate
Off Plan Properties Dubai

Thank you..
 
Extremely overall quite fascinating post. I was searching for this sort of data and delighted in perusing this one. Continue posting. A debt of gratitude is in order for sharing.data science institutes in Hyderabad
 
I really appreciate the kind of topics you post here. Thanks for sharing us a great information that is actually helpful. Good day!

Best Institute for Data Science in Hyderabad



 
I tell you one more time use youtube to explain it. On youtube more people will see your video. And you can get youtube likes from this site https://soclikes.com/ any time
 
Really, this article is truly one of the best, information shared was valuable and resourceful Very good work thank you.
Data Scientist Training in Hyderabad
 
Incredibly all around intriguing post. I was searching for such a data and completely appreciated inspecting this one. Continue posting. A commitment of gratefulness is all together for sharing.data science course in Hyderabad
 

I finally found a great article here. I just added your blog to my bookmarking sites looking forward for next blog thank you.
Data Science Course in Bangalore
 
Very interesting blog. Many blogs I see these days do not really provide anything that attracts others, but believe me the way you interact is literally awesome.You can also check my website as well.

p2gamer
Freelancers Marketplace

Thank you..
 
Hi, I have perused the greater part of your posts. This post is presumably where I got the most valuable data for my examination. Much obliged for posting, we can see more on this. Are you mindful of some other sites regarding this matter.
data scientist course
 
I am glad to discover this page. I have to thank you for the time I spent on this especially great reading !! I really liked each part and also bookmarked you for new information on your site.

Data Science Course in India
 
Attend The Data Analyst Course From ExcelR. Practical Data Analyst Course Sessions With Assured Placement Support From Experienced Faculty. ExcelR Offers The Data Analyst Course.
Data Analyst Course

 
Very interesting blog. Many blogs I see these days do not really provide anything that attracts others, but believe me the way you interact is literally awesome.You can also check my website as well.

Do my online test

Thank you..
 
Thanks for sharing this wonderful content. its very interesting. Many blogs I see these days do not really provide anything that attracts others but the way you have clearly explained everything it's really fantastic. There are lots of posts But your way of Writing is so Good & Knowledgeable. keep posting such useful information and have a look at my site as well

p2gamer
Freelancers Marketplace

Thank you..
 
Top quality blog with unique content and information shared was valuable looking forward for next updated thank you
Ethical Hacking Course in Bangalore
 
Thanks for sharing this wonderful content. its very interesting. Many blogs I see these days do not really provide anything that attracts others but the way you have clearly explained everything it's really fantastic. There are lots of posts But your way of Writing is so Good & Knowledgeable. keep posting such useful information and have a look at my site as well

Rowe Rowe yahoo news
Rowe Rowe Royal interval it shows

Thank you..
 
Very informative content and intresting blog post.Data science training in Mumbai
 
I have to search sites with relevant information ,This is a
wonderful blog,These type of blog keeps the users interest in
the website, i am impressed. thank you.
Data Science Course in Bangalore

 
Excellent information, thank you so much for sharing us this valuable information. Visit Ogen Infosystem for professional Website Designing and PPC Company in Delhi.
Website Designing Company in Delhi
 
Much obliged for sharing this superb substance. its extremely intriguing. Numerous web journals I see these days don't actually give whatever pulls in others however the manner in which you have plainly clarified everything it's truly phenomenal. There are loads of posts But your method of Writing is so Good and Knowledgeable. continue to post such helpful data and view my site also

Rehab Nashville

Thank you..
 
very informative blog
data science training in Pune
 
Specialized centre for immediate dental implants. We develop successful dental tourism in Bulgaria and offer our services in 12 languages to restore your smile beauty just in a single visit. We gathered all you need in one place, using the most advanced technologies (ISO certificate under EU rules): Radiography centre with the scanner, Panoramic X-Ray by 3D analysis, Dental x-ray machine for intraoral pictures. A dental laboratory specializing in prosthetics of dental implants. Eight dental cabinets with one VIP cabinet.
Our team consists of Implantologists-specialized in Basal implant, Oral Surgeons, Dentists, assistants, qualified Interpreters, cardiologists, radiologists, and anaesthetists who are at your disposal during the treatment. Want to know ?

Dental implants price
How much do dental implants cost

Visit us now! Thank you..
 
Thanks for sharing this wonderful content.its very interesting .Many blogs I see these days do not really provide anything that attracts others but the way you have clearly explained everything it's really fantastic.There are lots of posts But your way of Writing is so Good & Knowledgeable.keep posting such useful information and have a look at my site as well

Promo Codes,Coupon Codes,Coupons
Voucher Codes,Discount Codes,Online Promo Codes,Online Coupon Codes

Thank you..

 
Post a Comment



<< Home

This page is powered by Blogger. Isn't yours?