|
-
February 5th, 2010, 11:55 AM
#1
static factory...
Given:
Code:
#include <map>
#include <memory>
#include <exception>
#include <vector>
#include <iostream>
template <class Base, class Derived>
static Base* create()
{
std::cout << "." << std::endl;
return new Derived;
}
template <class Base, typename Key = int>
class SimpleFactory
{
// For simpler handling of the function pointer
typedef Base* (*create_func)();
// This map stores a creator function for a type
typedef std::map<Key, create_func> creator_map;
creator_map c_map_;
//static creator_map c_map_;
public:
template <class Derived>
void Register(Key const& key)
{
if (!c_map_.insert(std::make_pair<Key, create_func> (key, &create< Base, Derived> ) ).second)
throw 0; //throw something meaningful later
}
Base* GetInstance(Key const& key) const
{
typename creator_map::const_iterator iter = c_map_.find(key);
if (iter != c_map_.end())
return ( (iter->second)() ) ;
else
throw 0;
}
};
class B {
public:
virtual void Serialize() = 0; //more common to all Derived classes
//virtual void DeSerialize() = 0; //more common to all Derived classes
//more common to all Derived classes
virtual ~B() {}
};
class D1 :public B {
int index;
public:
D1() : index ( 0 ) {}
virtual ~D1() {}
void Serialize() {
index ++;
std::cout << "[Working=" << std::hex << index << " ]" << std::endl;
}
int GetIndex() {
return ( index ) ;
}
void Increment() { std::cout << "Doing it" << std::endl; }
//more functions specific to D1
};
class D2 :public B {
public:
virtual ~D2() {}
void Serialize() { std::cout << "Working" << std::endl; }
void DoAnotherThing() { std::cout << "Doing it" << std::endl; }
void Try() { std::cout << "Trying 2" << std::endl; }
};
int main() {
static SimpleFactory<B, int> simple;
simple.Register<D1>(1);
D1* ptr = static_cast< D1* > ( simple.GetInstance ( 1 ) );
ptr->Serialize();
D1* ptr2 = static_cast< D1* > ( simple.GetInstance ( 1 ) );
std::cout << "[] " << ptr2->GetIndex() << std::endl;
std::cin.get();
}
How do I get _any/all_ changes to D1 reflected in all instances (i.e ptr or ptr2) of D1 without making D1 a singleton? In other words. The call ptr2->GetIndex() should display 1 as opposed to zero since the member variable 'index' was incremented in the Serialize method.
Posting Permissions
- You may not post new threads
- You may not post replies
- You may not post attachments
- You may not edit your posts
-
Forum Rules
|
Click Here to Expand Forum to Full Width
|