Object Oriented Design -- Data and Algorithm Separation (1)(二)

2014-11-24 11:34:46 · 作者: · 浏览: 1
pe _data; };If any data type satisfies these requirements, it could be operated by the algorithm part disregarding the internal difference, and so the data and algorithm could be separated.


EXAMPLE:

In the header file below, I defined 2 different data structures to be used in the binary tree algorithm.
//
// FILE: data_def.h, defining data stuctures to be used in binary tree.
// Author: DGU, email: gdyxgzy@hotmail.com
// If you would like to use whole or part of this code or forward this article,
// please keep this header, and send an email to my inbox.
//
#ifndef DATA_DEF_HEADER
#define DATA_DEF_HEADER


#include 
  
   


class DataStruct1
{
public:
	typedef int key_type;
	typedef std::string data_type;


	//DataStruct1() : _key(0), _data(std::string()) {};
	DataStruct1(const key_type& k, const data_type& d) : _key(k), _data(d) {};


	const key_type get_key(void) const { return _key; };
	const data_type get_data(void) const { return _data; };
	//void set_data(const data_type& d) { _data = d; };


	//I used std::find in build_tree, so I need this == operator
	bool operator == (const DataStruct1& a) const { return _key==a._key; };


private:
	key_type _key;
	data_type _data;
};


class DataStruct2
{
public:
	typedef double key_type;
	typedef double data_type;


	//DataStruct2() : dbl(0.0) {};
	DataStruct2(double d) : dbl(d) {};


	const key_type get_key(void) const { return dbl; };
	const data_type get_data(void) const { return dbl; };
	//void set_data(double d) { dbl = d; };


	bool operator == (const DataStruct2& a) const { return dbl==a.dbl; };


private:
	double dbl;
};


//
// Well, you could define some other data structures here
//
#endif


// -------------- END OF THIS FILE --------------------//

  

Notes:

1. To use the algorithm, the data structure should at least have a default constructor, in these 2 test cases, because they are relatively simple, you even do not have to provide one. Also, to make object construction simpler, I provided a constructor with arguments each.

2. Another thing to be noted is the == operator. Actually it is not mandotary, it is only because that I used std::find() method in constructing the binary tree object, so I will need this operator.

3. Also, I require that the key must be unique in order to construct the trees(please see the comments in build_tree() in the following article), this requirement is not mandatory in real applications.


Above is the data definition part of this code, the binary tree and algorithm related code will be posted in the following article.

(To be continued ......)