Reference to Abstract Base Class

Started by
4 comments, last by theOcelot 14 years, 9 months ago
Hello to all, i would like to store a abstract base class in context class then based on the type being instantiated and called the concrete strategy algorithm. Is this possible ?


#ifndef ENCRYPTOR_H 
#define ENCRYPTOR_H

#include <boost/shared_ptr.hpp>
#include "EncryptionStrategy.h"


// Context in UML diagram
class Encryptor
{
private:
 boost::shared_ptr<encryptionStrategy> anEncryptor; 

public:
 Encryptor();
 ~Encryptor();

 void encrypt();

};


/*
C++ Implementation Variation
1. Constructor takes strategy pointer
2. Constructor takes null strategy pointer and create default concrete strategy
3. Template parameter



*/


#endif


Encryptor::Encryptor() 
: anEncryptor(boost::shared_ptr<encryptionStrategy>(new encryptionStrategy()) 
{
}


Thanks. Please help. EDIT: Constructor also can takes an abstract pointer then which indirectly return to concrete base class type. class encryptionStrategy is a strategy pattern abstract base class which derived from many concrete strategy class. I want to initialized anEncryptor without client passed the appropriate pointer to class Encryptor constructor. How to solve it ? Thanks.
Advertisement
I looking for alternative approach where doesn't require to create strategy object in main and passes it to encryptor constructor.

Perhaps i was wrong but learning from mistake is kind of experience.

Hope someone can explain overall strategy pattern and my coding style.

Thanks for your help.
I don't fully understand the question but ...

It looks to me that you want to look into templates.
Perhaps the "Curiously Recurring Template Pattern" could do the trick.
http://en.wikipedia.org/wiki/Curiously_Recurring_Template_Pattern

Or you you can create classes that derive from encryptionStrategy (which then becomes the base class) and have different implementations for the desired occasion.
If you want the base class to have a default implementation/strategy, you're just going to have to pick a concrete strategy class and instantiate it directly in the initializer list.

But what's the point of using the strategy pattern, if there's only ever going to be one strategy?
OK, Thanks for your reply. I misunderstood the strategy pattern and i thought i not need to instantiate concrete strategy pattern and pass to encryptor. Now i was wrong.

How about i don't want to uses dynamic allocated memory to initialize the encryptor member insted of some smart pointer ?

Thanks.

Quote:Original post by Peter_APIIT
How about i don't want to uses dynamic allocated memory to initialize the encryptor member insted of some smart pointer ?

Thanks.


What?

This topic is closed to new replies.

Advertisement