/*-
* Copyright (c) 2012 valsorym <valsorym.e@gmail.com>.
* All rights reserved.
*
* Discussion on the forums.freebsd.org.
* url: http://forums.freebsd.org/showthread.php?p=177208
*/
/*
* Very simple class, for example OOD in ANSI C.
*/
#include <stdio.h>
#include <string.h>
#include <memory.h>
#include "human.h"
/* INTERFACES */
/* Private:
* For the experiment, the method of Private.
*/
static int goodage(int );
/* Public: */
/* Constructor & Destructor */
static struct w_human *create(int , char *);
static void destroy(struct w_human *);
/* To access the data, we use the methods. */
static int setage(struct w_human *, int );
static int getage(struct w_human *);
static char *setname(struct w_human *, char *);
static char *getname(struct w_human *);
/* Initialization (constructor / destructor). */
const struct w_human_initializer w_human = {
.create = create, .destroy = destroy
};
/* IMPLEMENTATIONS */
/* Private: */
/*
* In this class, the method gooage() determines whether the normal
* age of a person.
*/
static int
goodage(int age)
{
if (age >= 0 && age <= 120)
return 1;
return 0;
}
/* Public: */
/*
* The constructor, allocates memory to accommodate the class,
* initialize its elements.
*/
static struct w_human
*create(int age, char *name)
{
struct w_human *self = (struct w_human *)malloc(sizeof(struct w_human));
/* Initialize the elements. */
/* Methods. */
self->setage = setage; self->getage = getage;
self->setname = setname; self->getname = getname;
/* Private data. */
self->setage(self, age);
self->setname(self, name);
return self;
}
/*
* The destructor frees the allocated memory in self class.
*/
static void
destroy(struct w_human *self)
{
if (self) {
if (self->name)
free(self->name);
free(self);
}
}
/*
* Set a person's age.
*/
static int
setage(struct w_human *self, int age)
{
if (self) {
if (goodage(age) == 0) /* Use function of private sector. */
return 0;
self->age = age;
}
return self->age;
}
/*
* Get the person's age.
*/
static int
getage(struct w_human *self)
{
if (self)
return self->age;
return 0;
}
/*
* Set the name of the person.
*/
static char
*setname(struct w_human *self, char *name)
{
int name_len = strlen(name) + 1;
if (self) {
if (self->name)
free(self->name);
self->name = (char *)malloc(name_len * sizeof(char));
strncpy(self->name, name, name_len);
return self->name;
}
return NULL;
}
/*
* Get the name of the person.
*/
static char
*getname(struct w_human *self)
{
if (self)
return self->name;
return NULL;
}
/* The End. */