Monday, October 15, 2007

Is Strategy Pattern any different than Polymorphism of OOPs

I am not sure if Strategy ( or Policy ) pattern is any different than simple use of Polymorphism with Encapsulation of OOPs theory.
So why should it be a part of GoF Design Pattern.
Comments welcome
Cheers,
Siddhartha

Thursday, October 4, 2007

Item 10 of More Effective C++ in an easy way

Though Scott's view is that I don't have RAII, but my approach saves un-necessary complications of using auto_ptr / smart_ptr. I respect Scott's view at the same time many people are not aware of the advantages of auto_ptr / smart_ptr and why to have more learning curve when a user doesn't want it at that time.

Basically I have initialized the pointers and then allocated memory to prevent resource leak during construction in the initialization list.
#include <iostream>
#include <string>
#include <list>
using namespace std;

class Image {
public:
Image(const string& imageDataFileName) {
fileName = imageDataFileName;
}
~Image() {
cout << "~Image()..." << endl;
}
private:
string fileName;
};

class AudioClip {
public:
AudioClip(const string& audioDataFileName) {
fileName = audioDataFileName;
throw exception();
}
~AudioClip() {
cout
<< "~AudioClip()..." << endl;
}
private:
string fileName;
};

class PhoneNumber {
public:
PhoneNumber(const int number) {
phNumber = number;
}
private:
int phNumber;
};

class BookEntry {
public:
BookEntry(const string& name,
const string& address = "",
const string& imageFileName = " ",
const string& audioClipFileName = " ") try : theName(name),theAddress(address),
// theImage(0),theAudioClip(0), // so sad that multiple initialization is not allowed Sad
theImage(imageFileName != ""
? theImage=0, new Image(imageFileName) //This is the trick ',' operator does the job
: 0),
theAudioClip(audioClipFileName != ""
? theAudioClip = 0,new AudioClip(audioClipFileName)
: 0) {
} catch(...) {
cout
<< "exception caught during construction of BookEntry..." << endl;
if(theImage) delete theImage;
if(theAudioClip) delete theAudioClip;
throw;
}

~BookEntry() {
delete theImage;
delete theAudioClip;
}
void addPhoneNumber ( const PhoneNumber& number);
private:
string theName;
string theAddress;
list
< PhoneNumber> thePhones;
Image *theImage;
AudioClip *theAudioClip;
};

int main() try {
cout
<< "Hello World!" << endl;
BookEntry bookEntry("sid");
return 0;
}
catch(exception &e) {
cout
<< " exception caught " << endl;
}
catch(...) {
cout
<< "Uncaught exception..." << endl;
}