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 thedata_object
. We are willing to take that extra burden if architecture 2 is much better than 1. -
We will not change algo type ever.
Aucun commentaire:
Enregistrer un commentaire