Introduction
This article gives a brief description of the Flyweight pattern through the use of a data validator for user interfaces. The function implementation of the validator is not relevant and is not demonstrated here. The sample code with three validators given here was compiled in VC6 with SP5 in NT 4.0.
Flyweight Pattern
As described in the book Design Patterns: Elements of Reusable Object-Oriented Software by Erich Gamma et al. ( Addison-Wesley, 1995 ) at page 195 (Also called GoF: Gang of Four): "Use sharing to support large numbers of fine grained objects efficiently".
Let's say you are developing UIs with lots of data validations (a good example is an editable List Control or a Grid) and you need to validate data entered by the user. In MFC applications you would override the command handler fired after the user ends data entry and validate the data for each UI element separately. Using the Flyweight pattern you write the validators once and you can easily add more validators through the development of your code.
How it works
The Flyweight has a pool of objects (also called a factory) and a function that returns a pointer to one of these objects when requested to do so. The way to request an object is through a key (in this example the getValidator
function) which receives the key of the object as a string and returns a pointer to it. That's it!!!
Code Sample
The purpose of the code in the demo project is to demonstrate the Flyweight pattern, therefore the implementation might not be exactly brilliant. All function implementations as well as class declarations are written together inside file DataValidator.h.
The CDataValidator base class
The CDataValidator
class is the base class for all validators. Notice that the ValidateString
function forces a validation algorithm by using two virtual functions CheckMinus
and CheckStringOrder
. This is called a Template Method. The description of this pattern as described in GoF at page 325 is: "Define the skeleton of an algorithm in an operation, deferring some steps to subclasses."
class CDataValidator
{
public:
CDataValidator(){}
virtual bool ValidateString(const CString& sToValidate)
{
if(!CheckMinus(sToValidate))
return false;
if(!CheckStringOrder(sToValidate))
return false;
return true;
}
virtual bool ValidateChar (const CString& cToValidate)=0;
protected:
bool CheckDoublesOrder(const CString& sToValidate)
{
if(sToValidate.IsEmpty())
return false;
if(sToValidate[0]=='-'&& sToValidate.GetLength()>2)
{
if(sToValidate[1]=='0' && sToValidate[2]!='.')
return false;
}
else
{
if(sToValidate[0]=='0' && sToValidate.GetLength()>1)
{
if(sToValidate[1]!='.')
return false;
}
return true;
}
return true;
}
bool CheckIntsOrder(const CString& sToValidate)
{
if(sToValidate.IsEmpty())
return false;
if(sToValidate[0]=='-' && sToValidate.GetLength()>1)
{
if(sToValidate[1]=='0')
return false;
}
else
{
if(sToValidate[0]=='0' && sToValidate.GetLength()>1)
return false;
}
return true;
}
virtual bool CheckMinus(const CString& sToValidate)
{
int index = sToValidate.Find("-");
if(index >0)
return false;
return true;
}
virtual bool CheckStringOrder(const CString& sToValidate)=0;
};
The CDataValidatorPool class
The pool holds all validator objects in an std::map
(I used and STL map
because it makes more sense to me). If an object does not exist the pointer returned by the getValidator
function is NULL.
class CDataValidatorPool
{
public:
CDataValidatorPool()
{
m_ValidatorPool["INT"] = new CIntValidator;
m_ValidatorPool["DBL"] = new CDoubleValidator;
m_ValidatorPool["STR"] = new CStringValidator;
}
~CDataValidatorPool()
{
std::map<CString,CDataValidator* >::iterator Iter;
for(Iter=m_ValidatorPool.begin();Iter!=m_ValidatorPool.end();++Iter)
{
delete m_ValidatorPool[Iter->first];
}
m_ValidatorPool.clear();
}
CDataValidator* getValidator(const CString& sValidatorName)
{
if(m_ValidatorPool.find(sValidatorName)!=m_ValidatorPool.end())
return m_ValidatorPool[sValidatorName];
else
return NULL;
}
private:
std::map<CString,CDataValidator* > m_ValidatorPool;
};
How to use it
If you want to use the code demonstrated here in your project insert the DataValidator.h file in your project, create a member variable of the class CDataValidatorPool
and of you go.
Optimizations
There are a few optimizations to this model depending on your implementation:
- You can make the pool object a Singleton (GoF page 127 as well as The Singleton Pattern in this site).
- You can create the objects on demand at the
getValidator
function instead of up front in the constructor.
- Each object can be a Singleton.
- You can add a reference count to each object.
Copyright 2001 ITG Israel LTD. All Rights Reserved.
Enjoy Programming!!!