View Single Post
Old 02-17-2005, 08:57 AM   #1 (permalink)
Valmont
[code][/code] enforcer
 
Valmont's Avatar
 
Join Date: Mar 2003
Location: Netherlands
Posts: 1,544
Valmont is on a distinguished road
Tip (5 minute solution): The Facade Pattern

The Facade Design Pattern

Often when code is presented by slightly less seasoned coders, they tend to overdo the main() function, by adding too much code in it. It only gets harder for strangers to find out what's going on.

Here is an example. We will implement the most basic linked list we can imagine:
Code:
#include <iostream>

struct IntNode
{
  int num_;
  IntNode* next_;
};

int main()
{
  IntNode *start, *p;
  start = 0;
  
  //Add a node.
  p =  start;
  start = new IntNode;
  start->next_ = p;
  start->num_ = 28;
  
  //Add another node.
  p =  start;
  start = new IntNode;
  start->next_ = p;
  start->num_ = 13;
  
  //Add another node.
  p =  start;
  start = new IntNode;
  start->next_ = p;
  start->num_ = -48;
  
  //Show the contents of the linked list. for(p = start; p != 0; p = p->next_)
  {
    std::cout<<p->num_<<", ";
  }
  std::cout<<std::endl;
  
  //Release the memory. while(start != 0)
  {
    p = start;
    start = start->next_;
    delete p;
  }
  
  return 0;
}
As you can see, the main() function is full of code. We should simply encapsulate some code so the big picture becomes clear in a blink of the eye. Just write a class that does all the difficult stuff. Let's make a Facade:
Code:
#include <iostream>

struct IntNode
{
  int num_;
  IntNode* next_;
};

//-------------------------------------------- class LinkedList
{
public:
  void AddItem(int itm);
  void ShowItems();
public:
  LinkedList() : start_(0){ }
  ~LinkedList();
private:
  IntNode* start_;
};

//-------------------------------------------- int main()
{
   LinkedList MyList;
  MyList.AddItem(28);
  MyList.AddItem(13);
  MyList.AddItem(-48);
  MyList.ShowItems();
  
  return 0;
}

//-------------------------------------------- void LinkedList::AddItem(int itm)
{
  IntNode* p = start_;
  start_ =  new IntNode;
  start_->next_ = p;
  start_->num_ = itm;
}

void LinkedList::ShowItems()
{
  for(IntNode* p =  start_; p != 0; p = p->next_)
  {
    std::cout<<p->num_<<", ";
  }
  std::cout<<std::endl;
}

LinkedList::~LinkedList()
{
  IntNode* p;
  while(start_ != 0)
  {
    p = start_;
    start_ = start_->next_;
    delete p;
  }
}
And now a stranger can concentrate on the big issues first.

Let's wrap it up:
Goal:
Hide the difficult stuff in a class (or more if needed).

Advantage:
Makes it client-friendly.

Disadvantage:
Client might have less "power-user" options.

That's it!
- Val -
__________________
Valmont is offline   Reply With Quote