// lazy initialization types.put(type,f);
return f;
C++ Przykład klasy Fruit napisanej w C++ #include <iostream> #include <string> #include <map>
using namespace std;
class Fruit { private: static map<string,Fruit*> types; string type;
// note: constructor private forcing one to use static getFruit() Fruit(const string& t) : type( t ) {}
public: static Fruit* getFruit(const string& type); static void printCurrentTypes();
//declaration needed for using any static member variable map<string,Fruit*> Fruit::types;
/* * Lazy Factory method, gets the Fruit instance associated with a * certain type. Instantiates new ones as needed. * precondition: type. Any string that describes a fruit type, e.g. "apple" * postcondition: The Fruit instance associated with that type. */ Fruit* Fruit::getFruit(const string& type) { map<string,Fruit*>::iterator iter = types.find(type); //try to find a pre-existing instance
if (iter == types.end()) { // couldn't find one, so make a new instance Fruit* f = new Fruit(type);