mandar jadhav
mandar jadhav

Reputation: 11

Suggest a best suitable design patten

I have a problem statement where I need to design classes in such a way that there behavior is decided at runtime.

The class heirarchy is as follows;

                       Base
          ______________|________________
         |           |        |         |      
       Drvd-A     DrvdB     DrvdC   Drvd-Generic  

An instance of type "Drvd-Generic" should inherit in principle the behavior of any of the classes "Drvd-A", "Drvd-B" or "Drvd-C" at runtime.

The behavior of instance "Drvd-Generic"will be decided at runtime and can be changed at runtime too. For instance; - created instance Drvd-Generic; - for a specific time and under certain conditions Drvd-Generic should inherit the behavior of Drvd-A; - after trigering some changes Drvd-Generic should inherit the behavior of Drvd-B;

This will happen at runtime under occurence of certain conditions and instance of Drvd-Generic will be same for the life time of program.

Suggest a best fit design pattern to suit the case.

Upvotes: 1

Views: 132

Answers (3)

TheSilverBullet
TheSilverBullet

Reputation: 625

How about a decorator pattern?

interface Base
{
//This is the interface which specifies the members
}
class Drvd-Generic : Base
{
//This implements the base class
}
class DrvdA : Base
{
//This class has a member of type Drvd-Generic
//The constructor accespts the Drvd-Generic object
//This can define DrvdA specific functions to further work on it.
//Basically this is the decorator class.
//As are DrvdB and DrvdC
}
class DrvdB : Base
{
}
class DrvdC : Base
{
}

Hope this helps you.

Upvotes: 0

Luchian Grigore
Luchian Grigore

Reputation: 258548

Seems like a strategy pattern w/ composition would work, where you have a member of type Behavior. (pseudocode follows)

class Behavior
{
   virtual execute() = 0;
}
class BehaviorA
{
   virtual execute();
}
//and others

class Base
{
   Behavior* behavior;
}
class Drvd-A : Base
{
   //set behavior to BehaviorA
}
//and others
class Drvd-Generic
{
   //set & change behavior at runtime
}

Upvotes: 1

GazTheDestroyer
GazTheDestroyer

Reputation: 21241

Drvd-Generic could implement the Strategy pattern, and use internal instances of DrvdA / DrvdB etc to do its work.

Upvotes: 2

Related Questions