Using a Function to Create Objects, Factory Pattern - C++ Design Pattern

C++ examples for Design Pattern:Factory Pattern

Description

Using a Function to Create Objects, Factory Pattern

Demo Code

#include <iostream>

class Session {};

class SessionFactory {

public:/*w  w w  .  ja  va  2  s . c  o  m*/
   Session Create();
   Session* CreatePtr();
   void Create(Session*& p);

};

// Return a copy of a stack object
Session SessionFactory::Create() {
   Session s;
   return(s);
}

// Return a pointer to a heap object
Session* SessionFactory::CreatePtr() {
   return(new Session());
}

// Update the caller's pointer with the address of a new object
void SessionFactory::Create(Session*& p) {
   p = new Session();
}

static SessionFactory f; // The one factory object

int main() {
   Session* p1;
   Session* p2 = new Session();

   *p2 = f.Create();
   p1 = f.CreatePtr();
   f.Create(p1);
}

Related Tutorials