Observer Pattern For Different Observables - c++

I was wondering what the appropriate way of dealing with Observables that may contain different data. To use the weather data analogy:
suppose I have different weather stations that record data. Let's say humidity, temperature and pressure. One station might only have the capability of recording temperature, while others all three etc..
What I am trying to do is the following:
An observer specifies what data they want to record. Say, only temperature.
An observable specifies what data they have available.
If both the observer and observable match up, the data is processed by the observable.
Here are a few things:
There are a lot more parameters than 3. Something like 30, and this can grow. I thought of implementing getTemperature(), getPressure(), getHumidity(), etc.. in my base observable and overriding them in the relevant classes. Otherwise it returns nothing. I also created a Flags anonymous struct that is specified for both the Observable and Observer, and only when they match data is recorded.
I wanted to know the following:
Is this the best design? Should the responsibility of matching Flags be on the Observer? Is there a more elegant solution?
I'm not necessarily looking for code handouts. Just thoughts on a good implementation.
Thanks!

Since you already have Flags that identifies the kinds of things that can be observed, i.e.
enum Measurement {
Temperature = 0x00001
, Humidity = 0x00002
, Pressure = 0x00004
};
you might reuse it to identify the measurements through data, as opposed to identifying them through method names. In other words, instead of making the interface that looks like this
struct observable {
Measurement provides() {
return Temperature | Humidity | Pressure;
}
double getTemperature() ...
double getHumidity() ...
double getPressure() ...
};
do it like this:
struct observable {
Measurement provides() {
return Temperature | Humidity | Pressure;
}
double measure(Measurement measurementId) {
...
}
};
This would give you a uniform interface, with observers and observables matched entirely through data.
However, all implementations of measure would need to "dispatch" based on a number in something that looks like a switch, which is not ideal. There is a solution to this: you could put a single, non-virtual implementation in the base class, and use regular virtual dispatch after that:
struct observable_base {
double measure(Measurement measurementId) {
switch(measurementId) {
case Temperature: return getTemperature();
case Humidity: return getHumidity();
case Pressure: return getPressure();
}
return 0;
}
protected:
virtual double getTemperature() { return 0; }
virtual double getHumidity() { return 0; }
virtual double getPressure() { return 0; }
};

From my experience, it's best to use Object-oriented design for the Observer pattern.
You can create an Observer < Weather > and an Observable < Weather > with a single object that is observed, a Weather object. Pseudocode sample:
public class Weather()
{
... Temperature
... Pressure
... Humidity
}
If a given implementation has more than one observable piece of data, just have it implement the Observable for that type also.
So, you could have a ColorableWeatherState object that is both Observable < Weather > and Observable < Color > and could be subscribed to by both observers who care about color and by observers who care about weather. They could be separate. They could be the same object. It's up to you to determine the implementation.

First of all, the following is my opinion. There are a lot of ways to solve your problem and maybe others are better. I tell you how I solute such kind of problems.
I would not define a base observable with all possible methods, that is bad style. A base class should only define Methods, it fulfill. Additionally it is hard to extend, you have to code observer and observables at the same time and have to compile it both. In case of using additional communication layers in the future, like networking, it is even harder to abstract.
If your values have the same type, use one getter method and give it a parameter to select the result:
double getValue(enumMyValueType type);
if you have different types, e.g. strings and doubles, I would use a kind of variants (like boost::variants) not like getValueDoublesand getValueString. Different getters only distinguished by type should be avoided in your case. Keep your observable class small and stable. Extending it with new values like color or oxygen is easy without recode the whole path if you use an own return type.
Defining an own return type class is better than define a big baseclass for observables as you can put together several information regarding to the value like:
temperature
source
timestamp
and
pressure
source
timestamp
extending the type do not affect your observer and observables they are still lightweight.
At last. Only the Observer should decide what he want and if he match or not. The observer should ask the observables and decide what and where to register. An observable should not need to know what the observer want. Any negotiation system I saw until now failed (in case of DirectShow it failed badly).

This might be a bad answer, but I wonder why can't we make observables return a struct of variables(or pointers to them), with invalid fields set to NaN(or Null for pointers) or some other identifier.
One problem I can see is that, it will force the observable to provide everything regardless what the observer requests.
Then what about:
On a get() call to observable, it returns a struct of function pointers to data getters. If the observable can provide that data, then the getter is not Null. Then the observer can pick a getter, check if it's null, then finall get the data it wants.

Related

Strategy pattern vs Inheritance

We have some algo to apply over some data, and the algo may get applied multiple times on same data. We have two ways to do this:
Keep data and logic seperate
class Algo{
public:
virtual int execute(data_object) = 0;
};
class AlgoX: public Algo{
public:
int execute(data_object);
};
class AlgoY: public Algo{
public:
int execute(data_object);
};
class Data{
public:
string some_values;
...
void* algo_specific_data; //It will contain some algo specific data (like state of algo)
Algo* algo_ptr; //Reference of Algo
int execute(){
algo_ptr->execute(this);
}
};
some_function(){
Data* data_object = create_data(algo_ptr, algo_specific_data); //A dummy function which creates an object of type data.
data_object->execute();
}
Bind data and logic by inheritance
class Data{
public:
string some_values;
...
virtual int execute() = 0;
};
class DataWithAlgoX : public Data{
public:
AlgoX_Relateddata algo_related_data; //some algo specific data (like state of algo)
int execute();
}
class DataWithAlgoY : public Data{
public:
AlgoY_Relateddata algo_related_data; //some algo specific data (like state of algo)
int execute();
}
some_function(){
Data* data_object = create_data(algo_type); //A dummy function which creates an object of type data.
data_object->execute();
}
Which design is better, if
We can change algo type between the multiple calls of algo->execute() on data
(But switching will not be very frequent, and needed only in some specific scenario).
Some people may point out that switching of algo will make us to recreate the data_object.
We are willing to take that extra burden if architecture 2 is much better than 1.
We will not change algo type ever between the multiple calls of algo->execute() on data .
Mixing Data and Algorithm in the same class in (very) bad practice.
In breaks the Single Resposability Principle.
https://en.wikipedia.org/wiki/Single_responsibility_principle
If you want to combine multiple types of Data with multiple Algorithms
use something like a Mediator. The idea is to define Data and Algorithms separately and define the interaction between them in the mediator.
https://en.wikipedia.org/wiki/Mediator_pattern
In my opinion, design 2 is MUCH worse then 1. And even in the case of design 1, I would remove the reference to the algorithm in the Data class. It only introduces High Coupling, i. e. a dependecy between the classes which make one affected bt the changes in the other:
https://en.wikipedia.org/wiki/Coupling_(computer_programming)
(and google "Low coupling, high cohesion", it is another OOP principle).
The Mediator would solve the coupling problem too.
I would prefer keeping Algo separate from Data always. In general Same data could be used for different Algo and same Algo can be used on different Data. So if you are implementing it as an inheritance chances are high that it will lead to code duplication or combinatorial explosion of subclasses like DataWithAgloA DataWithAlgoB.
More importantly Data provider i.e the system which generates data might not need to know about complex algorithms to be used there. It could be very well dumb system to generate data and there could be researchers who are updating the Algo. Keeping Data and Algo essentially violates Single Responsible Principle. Now your DataWithAlgo class has 2 axis of change (As uncle bob would say) from Algo and from Data.
Keeping Data and Algo separate keeps both the code nimble and easy to change and also satisfy SRP. This reduce coupling in the code, avoids any combinatorial explosion. So I would always go segregating Algo from Data.
Strategy pattern vs Inheritance
Between these two, favor the first over the latter. In inheritance, not only are you inheriting the API contract, you're also inheriting behavior, which may or may not be possible to override. And in your case, since you state that multiple algorithms may be applied to the same class today but not necessarily tomorrow, applying inheritance this way will lead to an explosion of classes and duplicate code, as you've shown.
However,
We have two ways to do this
How come? Have you considered the Decorator Pattern (my favorite)? Depending on how your data nodes are structured, perhaps even the Visitor Pattern is a valid choice.
I would also caution against the blanket "mixing data and algorithm always breaks SRP" advise generally thrown around. You introduce "2 axis of change" only when the use-case actually arises. Ideally, if you have perfect encapsulation, there is no reason why a type can't handle and apply algorithms to its own data. This depends on the domain; in your case, this clearly does not (seem to?) apply.

Pattern for choosing behaviour based on the types present in a collection derived objects

I have an collection of objects which represents a model of a system. Each of these objects derives from a base class which represents the abstract "component". I would like to be able to look at the system and choose certain behaviours based on what components are present and in what order.
For the sake of argument, let's call the base class Component and the actual components InputFilter, OutputFilter and Processor. Systems that we can deal with are ones with a Processor and one or both filters. The actual system has more types and more complex interaction between them, but I think this will do for now.
I can see two "simple" ways to handle this situation with a marshalComponentSettings() function which takes one of the collections and works out how to most efficiently set up each node. This may require modifying inputs in certain ways or splitting them up differently, so it's not quite as simple as just implementing a virtual handleSettings() function per component.
The first is to report a enumerated type from each class using a pure virtual function and use those to work out what to do, dynamic_cast'ing where needed to access component specific options.
enum CompType {
INPUT_FILTER,
OUTPUT_FILTER,
PROCESSOR
}
void marshal(Settings& stg)
{
if (comps[0].type() == INPUT_FILTER)
setUpInputFilter(stg); //maybe modified the stg, or provides other feedback of what was done
// something similar for outputs
setUpProcessor(stg);
}
The second is to dynamic_cast to anything that might be an option in this function and use the success of that or not (as well as maybe the cast object if needed) to determine what to do.
void marshal(Settings& stg)
{
if (InputFilter* filter = dynamic_cast<InputFilter*>(comp[0]))
setUpInputFilter(stg); //maybe modified the stg, or provides other feedback of what was done
// something similar for outputs
setUpProcessor(stg);
}
It seems that the first is the most efficient way (don't need to speculatively test each object to find out what it is), but even that doesn't quite seem right (maybe due to the annoying details of how those devices affect each other leaking into the general marshaling code).
Is there a more elegant way to handle this situation than a nest of conditionals determining behaviour? Or even a name for the situation or pattern?
Your scenario seems an ideal candidate for the visitor design pattern, with the following roles (see UML schema in the link):
objectStructure: your model, aka collection of Component
element: your Component base class
concreteElementX: your actual components (InputFilter, OutputFilter, Processor, ...)
visitor: the abstract family of algorithms that has to manage your model as a consistent set of elements.
concreteVisitorA: your configuration process.
Main advantages:
Your configuration/set-up corresponds to the design pattern's intent: an operation to be performed on the elements of an object structure. Conversely, this pattern allows you to take into consideration the order and kind of elements encountered during the traversal, as visitors can be stateful.
One positive side effect is that the visitor pattern will give your desing the flexibility to easily add new processes/algortihms with similar traversals but different purpose (for example: pricing of the system, material planning, etc...)
class Visitor;
class Component {
public:
virtual void accept(class Visitor &v) = 0;
};
class InputFilter: public Component {
public:
void accept(Visitor &v) override; // calls the right visitor function
};
...
class Visitor
{
public:
virtual void visit(InputFilters *c) = 0; // one virtual funct for each derived component.
virtual void visit(Processor *c) = 0;
...
};
void InputFilter::accept(Visitor &v)
{ v.visit(this); }
...
class SetUp : public Visitor {
private:
bool hasProcessor;
int impedenceFilter;
int circuitResistance;
public:
void visit(InputFilters *c) override;
void visit(Processor *c) override;
...
};
Challenge:
The main challenge you'll have for the visitor, but with other alternatives as well, is that the setup can change the configuration itself (replacing component ? change of order), so that you have to take care of keeping a consitent iterator on the container while making sure not to process items several time.
The best approach depends on the type of the container, and on the kind of changes that your setup is doing. But you'll certainly need some flags to see which element was already processed, or a temporary container (either elements processed or elements remaining to be processed).
In any case, as the visitor is a class, it can also encapsulate any such state data in private members.

Accessing subclass functions of member of collection of parent class objects

(Refer Update #1 for a concise version of the question.)
We have an (abstract) class named Games that has subclasses, say BasketBall and Hockey (and probably many more to come later).
Another class GameSchedule, must contain a collection GamesCollection of various Games objects. The issue is that we would, at times, like to iterate only through the BasketBall objects of GamesCollection and call functions that are specific to it (and not mentioned in the Games class).
That is, GameSchedule deals with a number of objects that broadly belong to Games class, in the sense that they do have common functions that are being accessed; at the same time, there is more granularity at which they are to be handled.
We would like to come up with a design that avoids unsafe downcasting, and is extensible in the sense that creating many subclasses under Games or any of its existing subclasses must not necessitate the addition of too much code to handle this requirement.
Examples:
A clumsy solution that I came up with, that doesn't do any downcasting at all, is to have dummy functions in the Game class for every subclass specific function that has to be called from GameSchedule. These dummy functions will have an overriding implementation in the appropriate subclasses which actually require its implementation.
We could explicitly maintain different containers for various subclasses of Games instead of a single container. But this would require a lot of extra code in GameSchedule, when the number of subclasses grow. Especially if we need to iterate through all the Games objects.
Is there a neat way of doing this?
Note: the code is written in C++
Update# 1: I realized that the question can be put in a much simpler way. Is it possible to have a container class for any object belonging to a hierarchy of classes? Moreover, this container class must have the ability to pick elements belonging to (or derive from) a particular class from the hierarchy and return an appropriate list.
In the context of the above problem, the container class must have functions like GetCricketGames, GetTestCricketGames, GetBaseballGame etc.,
This is exactly one of the problems that The "Tell, Don't Ask" principle was created for.
You're describing an object that holds onto references to other objects, and wants to ask them what type of object they are before telling them what they need to do. From the article linked above:
The problem is that, as the caller, you should not be making decisions based on the state of the called object that result in you then changing the state of the object. The logic you are implementing is probably the called object’s responsibility, not yours. For you to make decisions outside the object violates its encapsulation.
If you break the rules of encapsulation, you not only introduce the runtime risks incurred by rampant downcasts, but also make your system significantly less maintainable by making it easier for components to become tightly coupled.
Now that that's out there, let's look at how the "Tell, Don't Ask" could be applied to your design problem.
Let's go through your stated constraints (in no particular order):
GameSchedule needs to iterate over all games, performing general operations
GameSchedule needs to iterate over a subset of all games (e.g., Basketball), to perform type-specific operations
No downcasts
Must easily accommodate new Game subclasses
The first step to following the "Tell, Don't Ask" principle is identifying the actions that will take place in the system. This lets us take a step back and evaluate what the system should be doing, without getting bogged down into the details of how it should be doing it.
You made the following comment in #MarkB's answer:
If there's a TestCricket class inheriting from Cricket, and it has many specific attributes concerning the timings of the various innings of the match, and we would like to initialize the values of all TestCricket objects' timing attributes to some preset value, I need a loop that picks all TestCricket objects and calls some function like setInningTimings(int inning_index, Time_Object t)
In this case, the action is: "Initialize the inning timings of all TestCricket games to a preset value."
This is problematic, because the code that wants to perform this initialization is unable to differentiate between TestCricket games, and other games (e.g., Basketball). But maybe it doesn't need to...
Most games have some element of time: Basketball games have time-limited periods, while Baseball games have (basically) innings with basically unlimited time. Each type of game could have its own completely unique configuration. This is not something we want to offload onto a single class.
Instead of asking each game what type of Game it is, and then telling it how to initialize, consider how things would work if the GameSchedule simply told each Game object to initialize. This delegates the responsibility of the initialization to the subclass of Game - the class with literally the most knowledge of what type of game it is.
This can feel really weird at first, because the GameSchedule object is relinquishing control to another object. This is an example of the Hollywood Principle. It's a completely different way of solving problems than the approach most developers initially learn.
This approach deals with the constraints in the following ways:
GameSchedule can iterate over a list of Games without any problem
GameSchedule no longer needs to know the subtypes of its Games
No downcasting is necessary, because the subclasses themselves are handling the subclass-specific logic
When a new subclass is added, no logic needs to be changed anywhere - the subclass itself implements the necessary details (e.g., an InitializeTiming() method).
Edit: Here's an example, as a proof-of-concept.
struct Game
{
std::string m_name;
Game(std::string name)
: m_name(name)
{
}
virtual void Start() = 0;
virtual void InitializeTiming() = 0;
};
// A class to demonstrate a collaborating object
struct PeriodLengthProvider
{
int GetPeriodLength();
}
struct Basketball : Game
{
int m_period_length;
PeriodLengthProvider* m_period_length_provider;
Basketball(PeriodLengthProvider* period_length_provider)
: Game("Basketball")
, m_period_length_provider(period_length_provider)
{
}
void Start() override;
void InitializeTiming() override
{
m_period_length = m_time_provider->GetPeriodLength();
}
};
struct Baseball : Game
{
int m_number_of_innings;
Baseball() : Game("Baseball") { }
void Start() override;
void InitializeTiming() override
{
m_number_of_innings = 9;
}
}
struct GameSchedule
{
std::vector<Game*> m_games;
GameSchedule(std::vector<Game*> games)
: m_games(games)
{
}
void StartGames()
{
for(auto& game : m_games)
{
game->InitializeTiming();
game->Start();
}
}
};
You've already identified the first two options that came to my mind: Make the base class have the methods in question, or maintain separate containers for each game type.
The fact that you don't feel these are appropriate leads me to believe that the "abstract" interface you provide in the Game base class may be far too concrete. I suspect that what you need to do is step back and look at the base interface.
You haven't given any concrete example to help, so I'm going to make one up. Let's say your basketball class has a NextQuarter method and hockey has NextPeriod. Instead, add to the base class a NextGameSegment method, or something that abstracts away the game-specific details. All the game-specific implementation details should be hidden in the child class with only a game-general interface needed by the schedule class.
C# supports reflections and by using the "is" keyword or GetType() member function you could do these easily. If you are writing your code in unmanaged C++, I think the best way to do this is add a GetType() method in your base class (Games?). Which in its turn would return an enum, containing all the classes that derive from it (so you would have to create an enum too) for that. That way you can safely determine the type you are dealing with only through the base type. Below is an example:
enum class GameTypes { Game, Basketball, Football, Hockey };
class Game
{
public:
virtual GameTypes GetType() { return GameTypes::Game; }
}
class BasketBall : public Game
{
public:
GameTypes GetType() { return GameTypes::Basketball; }
}
and you do this for the remaining games (e.g. Football, Hockey). Then you keep a container of Game objects only. As you get the Game object, you call its GetType() method and effectively determine its type.
You're trying to have it all, and you can't do that. :) Either you need to do a downcast, or you'll need to utilize something like the visitor pattern that would then require you to do work every time you create a new implementation of Game. Or you can fundamentally redesign things to eliminate the need to pick the individual Basketballs out of a collection of Games.
And FWIW: downcasting may be ugly, but it's not unsafe as long as you use pointers and check for null:
for(Game* game : allGames)
{
Basketball* bball = dynamic_cast<Basketball*>(game);
if(bball != nullptr)
bball->SetupCourt();
}
I'd use the strategy pattern here.
Each game type has its own scheduling strategy which derives from the common strategy used by your game schedule class and decouples the dependency between the specific game and game schedule.

Alternatives to passing a flag into a method?

Sometimes when fixing a defect in an existing code base I might (often out of laziness) decide to change a method from:
void
MyClass::foo(uint32_t aBar)
{
// Do something with aBar...
}
to:
void
MyClass::foo(uint32_t aBar, bool aSomeCondition)
{
if (aSomeCondition)
{
// Do something with aBar...
}
}
During a code review a colleague mentioned that a better approach would be to sub-class MyClass to provide this specialized functionality.
However, I would argue that as long as aSomeCondition doesn't violate the purpose or cohesion of MyClass it is an acceptable pattern to use. Only if the code became infiltrated with flags and if statements would inheritance be a better option, otherwise we would be potentially be entering architecture astronaut territory.
What's the tipping point here?
Note: I just saw this related answer which suggests that an enum may be a better
choice than a bool, but I think my question still applies in this case.
There is not only one solution for this kind of problem.
Boolean has a very low semantic. If you want to add in the future a new condition you will have to add a new parameter...
After four years of maintenance your method may have half a dozen of parameters, if these parameters are all boolean it is very nice trap for maintainers.
Enum is a good choice if cases are exclusive.
Enums can be easily migrated to a bit-mask or a context object.
Bit mask : C++ includes C language, you can use some plain old practices. Sometime a bit mask on an unsigned int is a good choice (but you loose type checking) and you can pass by mistake an incorrect mask. It is a convenient way to move smoothly from a boolean or an enum argument to this kind of pattern.
Bit mask can be migrated with some effort to a context-object. You may have to implement some kind of bitwise arithmetics such as operator | and operator & if you have to keep a buildtime compatibility.
Inheritence is sometime a good choice if the split of behavior is big and this behavior IS RELATED to the lifecycle of the instance. Note that you also have to use polymorphism and this is may slow down the method if this method is heavily used.
And finally inheritence induce change in all your factory code... And what will you do if you have several methods to change in an exclusive fashion ? You will clutter your code of specific classes...
In fact, I think that this generally not a very good idea.
Method split : Another solution is sometime to split the method in several private and provide two or more public methods.
Context object : C++ and C lack of named parameter can be bypassed by adding a context parameter. I use this pattern very often, especially when I have to pass many data across level of a complex framework.
class Context{
public:
// usually not a good idea to add public data member but to my opinion this is an exception
bool setup:1;
bool foo:1;
bool bar:1;
...
Context() : setup(0), foo(0), bar(0) ... {}
};
...
Context ctx;
ctx.setup = true; ...
MyObj.foo(ctx);
Note:
That this is also useful to minimize access (or use) of static data or query to singleton object, TLS ...
Context object can contain a lot more of caching data related to an algorithm.
...
I let your imagination run free...
Anti patterns
I add here several anti pattern (to prevent some change of signature):
*NEVER DO THIS *
*NEVER DO THIS * use a static int/bool for argument passing (some people that do that, and this is a nightmare to remove this kind of stuff). Break at least multithreading...
*NEVER DO THIS * add a data member to pass parameter to method.
Unfortunately, I don't think there is a clear answer to the problem (and it's one I encounter quite frequently in my own code). With the boolean:
foo( x, true );
the call is hard to understand .
With an enum:
foo( x, UseHigherAccuracy );
it is easy to understand but you tend to end up with code like this:
foo( x, something == someval ? UseHigherAccuracy : UseLowerAccuracy );
which is hardly an improvement. And with multiple functions:
if ( something == someval ) {
AccurateFoo( x );
}
else {
InaccurateFoo( x );
}
you end up with a lot more code. But I guess this is the easiest to read, and what I'd tend to use, but I still don't completely like it :-(
One thing I definitely would NOT do however, is subclass. Inheritance should be the last tool you ever reach for.
The primary question is if the flag affects the behaviour of the class, or of that one function. Function-local changes should be parameters, not subclasses. Run-time inheritance should be one of the last tools reached for.
The general guideline I use is: if aSomeCondition changes the nature of the function in a major way, then I consider subclassing.
Subclassing is a relatively large effort compared to adding a flag that has only a minor effect.
Some examples:
if it's a flag that changes the direction in which a sorted collection is returned to the caller, that's a minor change in nature (flag).
if it's a one-shot flag (something that affects the current call rather than a persistent change to the object), it should probably not be a subclass (since going down that track is likely to lead to a massive number of classes).
if it's a enumeration that changes the underlying data structure of your class from array to linked list or balanced tree, that's a complex change (subclass).
Of course, that last one may be better handled by totally hiding the underlying data structure but I'm assuming here that you want to be able to select one of many, for reasons such as performance.
IMHO, aSomeCondition flag changes or depends on the state of current instance, therefore, under certain conditions this class should change its state and handle mentioned operation differently. In this case, I can suggest the usage of State Pattern. Hope it helps.
I would just change code:
void MyClass::foo(uint32_t aBar, bool aSomeCondition)
{
if (aSomeCondition)
{
// Do something with aBar...
}
}
to:
void MyClass::foo(uint32_t aBar)
{
if (this->aSomeCondition)
{
// Do something with aBar...
}
}
I always omit bool as function parameter and prefer to put into struct, even if I would have to call
myClass->enableCondition();

Inheritance vs specific types in Financial Modelling for cashflows

I have to program some financial applications where I have to represent a schedule of flows. The flows can be of 3 types:
fee flow (just a lump payment at some date)
floating rate flow (the flow is dependant of an interest rate to be determined at a later date)
fixed rate flow (the flow is dependant of an interest rate determined when the deal is done)
I need to keep the whole information and I need to represent a schedule of these flows.
Originally I wanted to use inheritance and create three classes FeeFlow, FloatingFlow, FixedFlow all inheriting from ICashFlow and implement some method GetFlowType() returning an enum then I could dynamic_cast the object to the correct type.
That would allow me to have only one vector<IFlow> to represent my schedule.
What do you think of this design, should I rather use three vectors vector<FeeFlow>, vector<FloatingFlow> and vector<FixedFlow> to avoid the dynamic casts ?
Why do you actually need the dynamic casts? Make your flow subclasses implement the same interface polymorphically, then there is no need to cast anything.
If they need very different inputs, you could try passing the different inputs as constructor parameters, thus clearing up the common interface. However, if you really can't define a common interface for them, maybe they are better implemented as independent classes.
If all the operations you need to do with the different types of the flow differ only by the underlying data, i would suggest extending the ICashFlow with such operations - then no dynamic casting is needed. If however this is not possible, then both options are ok i think. I personally would choose the one with the three vectors, if there is no other hidden need for one vector of base classes.
I think the strategy pattern would suit you best.
You implement a CashFlow class that contains a CashFlowStrategy property which does the processing.
I do not fully understand the requirements and the differences between the flows but something like this might work (meta-c++, not valid code):
class CashFlowStrategy {
public:
virtual void ProcessFlow(Account from, Account to);
}
class FixedRateCashFlowStrategy : public CashFlowStrategy {
public:
void ProcessFlow(Account from, Account to) { ... }
}
class CashFlow {
private:
CashFlowStrategy strategy;
public:
CashFlow(CashFlowStrategy &strategy) { this->strategy = strategy; }
void Process() { this->strategy->ProcessFlow(this->from, this->to); }
}
You only need the std::vector<CashFlow>, the decision of how to do the processing is hidden in the strategy so you shouldn't have to care about it.
It sounds like you have various schedules and various types of deposits, which collectively make up a financial flow. The solution sounds as if a strategy pattern may work for both schedule and deposit behavior. Although, if you have room, it might be worth considering a functional approach. A lambda expression would give you the same logic with a tenth of the code ...