Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #pragma once
- #include "My_types.h"
- class Factory {
- public:
- static Factory & getInstance(){return factory_;};
- unsigned int registerFigure(CreateFigure fun); //dodaje element do kolekcji,
- void read_data (std::ifstream &input,My_vector &v );
- Figure * Create(unsigned int id);
- private:
- static unsigned int ID_;
- static Factory factory_;
- //mapa przechowujaca pary id - klasy, wskaznik na funcje tworzaca obiekt
- //jej definicja w pliku naglowkowym My_types.h
- My_map fig_creators_;
- Factory(){};
- };
- #pragma once
- #include "Figure.h"
- #include <vector>
- #include <map>
- typedef Figure * (*CreateFigure)(); //wskaznik na funkcje tworzaca obiekt
- typedef std::vector <Figure *> My_vector;
- typedef std::map<unsigned int, CreateFigure> My_map; //mapowanie pomiedzy identfikatorem a typem
- /*
- * Rectangle.h
- *
- */
- #pragma once
- #include "Figure.h"
- class Rectangle: public Figure {
- public:
- Rectangle();
- Rectangle(float a, float b):A_(a),B_(b){};
- virtual ~Rectangle();
- void read(std::ifstream & input);
- void save (std::ofstream & output);
- void info();
- static Figure * CreateRectangle(){return new Rectangle();};
- static unsigned int id_;
- private:
- float A_,B_;
- };
- /*
- * Factory.cpp
- *
- */
- #include "Factory.h"
- unsigned int Factory::registerFigure(CreateFigure fun)
- {
- //metoda automatycznie zwieksza licznikk ID_ i
- //zapisuje pare
- fig_creators_.insert(std::pair<unsigned int,CreateFigure>(++ID_,fun));
- //wynik zwracany przechowywany przez kazda klase w polu statycznym id_
- return ID_;
- }
- Figure * Factory::Create(unsigned int id)
- {
- //Metoda na podstawie id tworzy nowy obiekt
- My_map::iterator it=fig_creators_.find(id);
- if (it!=fig_creators_.end())
- {
- return (it->second)();
- }
- return 0L;
- }
- void Factory::read_data (std::ifstream &input, My_vector & v)
- {
- //zmienne lokalne
- unsigned int type;
- Figure * tempFigure;
- while(!input.eof())
- {
- type=0;
- //odczytujemy id_ klasy
- input>>type;
- //tu tworzymy nowy obiekt
- tempFigure=Create(type);
- if (tempFigure!=0L)
- {
- //odczytanie danych juz do konkretnego obiektu
- //kozystamy tu z potegi funkcji wiryalnych
- tempFigure->read(input);
- //wczytany obiekt (tak naprawde wskaznik do niego) umieszczamy w wektorze
- v.push_back(tempFigure);
- }
- }
- }
- unsigned int Factory::ID_=1;
- Factory Factory::factory_;
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement