Singleton: Difference between revisions

Content added Content deleted
(Added PHP implementation - forgot the header last time, like the idiot that I am.)
(Adding C)
Line 119: Line 119:
end Protected_Singleton;</lang>
end Protected_Singleton;</lang>
{{omit from|AutoHotkey}}
{{omit from|AutoHotkey}}
=={{header|C}}==
Since C doesn't really support classes anyhow, there's not much to do. If you want somethin akin to a singleton, what you do is first declare the interface functions in a header (.h) file.
<lang c>#ifndef SILLY_H
#define SILLY_H

extern void JumpOverTheDog( int numberOfTimes);
extern int PlayFetchWithDog( float weightOfStick);

#endif</lang>
Then in a separate C source (.c) file, define your structures, variables and functions.
<lang c>...
#include "silly.h"

struct sDog {
float max_stick_weight;
int isTired;
int isAnnoyed;
};

static struct sDog lazyDog = { 4.0, 0,0 };

/* define functions used by the functions in header as static */
static int RunToStick( )
{...
}
/* define functions declared in the header file.

void JumpOverTheDog(int numberOfTimes)
{ ...
}
int PlayFetchWithDog( float weightOfStick )
{ ...
}</lang>
Code using the singleton includes the header and cannot create a
struct sDog as the definition is only in the C source (or other header privately included by the silly.c source). Only the functions declared in the header may be used externally.

=={{header|C++}}==
=={{header|C++}}==