4.2 Provider

The provider of an ADT contains the actual definitions and implementation of the ADT. This should be contained in a .c file. The provider is the engineer/designer of the ADT, which means it needs access to the actual implementation of an ADT. In our example, we may have the following:

#include "frac.h"
struct _Frac
{
  unsigned numerator;
  unsigned denominator;
};

inline struct _Frac *_FracCast(struct Frac *p)
{
  return (struct _Frac *)p;
}

struct Frac *newFrac(void)
{
  return (struct Frac *)malloc(sizeof(struct _Frac));
}

void delFrac(struct Frac *p)
{
  free(p);
}

void Frac_mult(struct Frac *n1, struct Frac *n2, struct Frac *product)
{
  _FracCast(product)->numerator = _FracCast(n1)->numerator * _FracCast(n2)->numerator;
  Frac_simplify(_FracCast(product);
}

float Frac_value(struct Frac *n)
{
  return (float)_FracCast(n)->numerator / _FracCast(n)->denominator;
}

// ...

To save typing, I defined an inline function to cast a pointer to a struct Frac to that of a struct _Frac.

Note that the producer only needs to make the header file frac.h and the object file frac.o available to consumers. This means the actual implementation source file, frac.c does not need to be distributed.



Copyright © 2006-09-07 by Tak Auyeung