www.developer.com/ws/brew/article.php/3355691
|
May 19, 2004 The following is a non-exhaustive list of recurring idioms in BREW, considered mainly from a C++ perspective. This is by no means a new enterprise, but the existing information is mostly scattered in articles, the BREW Forum[1], or knowledge bases[2][3]. The initial title was "Design Patterns in BREW," but the term "idiom" was finally preferred, largely because idioms are defined as low-level patterns specific to one language and this is exactly what this article wants to be about. Two of the idioms presented in this installment, "Stack Starvation" and "EverLoad," are fairly common and their implementation is (almost) trivial. The third one, "Static Is Dynamic," needs more attention and raises some interesting problems. Stack StarvationProblem:
Context:
Forces:
Solution:
Example:
struct STR{...};
bool f(/*const STR s - it copies STR on stack*/ const STR& s )
{
//char a[300]; avoid, expensive
char* a = new char[300];
//while (f(s)) {}; recursion
delete[] a; //don't forget to deallocate - error prone
}
Resulting Context:
Related Patterns: Smart Pointers, Pooled Allocation, Variable Allocation, EverLoad Static Is DynamicProblem:
Context:
Forces:
Solution:
Example: Cppapp is the application class in subsequent examples.
class CPPApp : public AEEApplet
{
//other members omitted for brevity
//... ...
public:
static CPPApp* getInstance()
{
return (CPPApp*)GETAPPINSTANCE();
}
private:
CPPApp( const CPPApp&);
const CPPApp& operator=( const CPPApp&);
private:
int sharedValue;
friend Singleton;
Singleton * b_;
};
boolean CPPApp::OnAppInitData()
{
b_ = new Singleton (2);
//...
return TRUE;
}
void CPPApp::OnAppfreeData()
{
delete b_;
//....
}
struct Singleton
{
static Singleton * getInstance()
{
CPPApp* c = CPPApp::getInstance();
return c->b_;
}
int getValue()
{
return i_;
}
private:
friend CPPApp;
Singleton (int i) : i_(i)
{}
private:
int i_;
};
struct Test
{
void test1()
{
Singleton * b = Singleton::getInstance();
b->getValue();
Singleton * bb = Singleton::getInstance();
bb->getValue();
// Singleton * bbb = new Singleton (11); //doesn't compile
}
static int& shared()
{
return CPPApp::getInstance->sharedValue;
}
};
The reference returned by shared() behaves fundamentally like a static value. Because there is only one instance of CPPApp, there will be only one instance of sharedValue and implicitly one value for the refernce returned by shared(). There are problems with this approach, as we will see later, but the overall the solution is satisfactory. Let's see how this applies to Singleton, a pattern based on an internally kept static instance[5][6]. Usually, we express a Singleton like this:
struct Singleton
{
static Singleton* getInstance()
{
if (!instance_ )
instance_ = new Singleton;
return instance_;
}
private:
static Singleton* instance_;
private:
Singleton(){}
};
Singleton* Singleton::instance_ = 0;
|