├── iterator.hpp ├── .gitignore ├── prototype.hpp ├── singleton.hpp ├── command.hpp ├── proxy.hpp ├── facade.hpp ├── object_adapter.hpp ├── decorator.hpp ├── factory_method.hpp ├── flyweight.hpp ├── LICENSE ├── class_adapter.hpp ├── adapter.hpp ├── pool.hpp ├── bridge.hpp ├── composite.hpp ├── mediator.hpp ├── holder.hpp ├── README.md ├── observer.hpp ├── chain_of_responsibility.hpp ├── vector.hpp ├── abstract_factory.hpp ├── set.hpp ├── array.hpp └── list.hpp /iterator.hpp: -------------------------------------------------------------------------------- 1 | #ifndef ITERATOR_HPP 2 | #define ITERATOR_HPP 3 | struct Node 4 | { 5 | Type Info; 6 | node* next; 7 | }; 8 | 9 | struct list 10 | { 11 | node* first, *last; 12 | node *current; //-> 13 | }; 14 | 15 | struct Iterator 16 | { 17 | node* current; 18 | }; 19 | #endif // ITERATOR_HPP 20 | -------------------------------------------------------------------------------- /.gitignore: -------------------------------------------------------------------------------- 1 | # Compiled Object files 2 | *.slo 3 | *.lo 4 | *.o 5 | *.obj 6 | 7 | # Precompiled Headers 8 | *.gch 9 | *.pch 10 | 11 | # Compiled Dynamic libraries 12 | *.so 13 | *.dylib 14 | *.dll 15 | 16 | # Fortran module files 17 | *.mod 18 | *.smod 19 | 20 | # Compiled Static libraries 21 | *.lai 22 | *.la 23 | *.a 24 | *.lib 25 | 26 | # Executables 27 | *.exe 28 | *.out 29 | *.app 30 | -------------------------------------------------------------------------------- /prototype.hpp: -------------------------------------------------------------------------------- 1 | #ifndef PROTOTYPE_HPP 2 | #define PROTOTYPE_HPP 3 | 4 | class Meal { 5 | public: 6 | virtual ~Meal(); 7 | virtual void eat() = 0; 8 | virtual Meal *clone() const = 0; 9 | // ... 10 | }; 11 | 12 | class Spaghetti : public Meal { 13 | public: 14 | Spaghetti( const Spaghetti & ); 15 | void eat(); 16 | Spaghetti *clone() const { return new Spaghetti( *this ); } 17 | //... 18 | }; 19 | 20 | #endif // PROTOTYPE_HPP 21 | -------------------------------------------------------------------------------- /singleton.hpp: -------------------------------------------------------------------------------- 1 | #ifndef SINGLETON_HPP 2 | #define SINGLETON_HPP 3 | template 4 | class Singleton 5 | { 6 | public: 7 | static T& instance() 8 | { 9 | if(myInstance == nullptr) 10 | myInstance = new T; 11 | return *myInstance; 12 | } 13 | private: 14 | static T* myInstance; 15 | Singleton() = delete; 16 | Singleton(const Singleton&) = delete; 17 | }; 18 | 19 | template 20 | T* Singleton::myInstance = nullptr; 21 | 22 | #endif // SINGLETON_HPP 23 | -------------------------------------------------------------------------------- /command.hpp: -------------------------------------------------------------------------------- 1 | #ifndef COMMAND_HPP 2 | #define COMMAND_HPP 3 | class Command //базовый класс команды 4 | { 5 | public: 6 | virtual ~Command(); 7 | virtual bool execute() = 0; 8 | protected: 9 | Command() {} 10 | }; 11 | 12 | template 13 | class SimpleCommand: public Command 14 | { 15 | private: 16 | typedef bool (Reciever::*Action)(); 17 | Reciever* rec; //указатель на объект 18 | Action act; //указатель на метод 19 | 20 | public: 21 | SimpleCommand(Reciever* r, Action a); //конструктор 22 | bool execute() //экзекутор 23 | { 24 | return (rec->*act)(); 25 | } 26 | }; 27 | #endif // COMMAND_HPP 28 | -------------------------------------------------------------------------------- /proxy.hpp: -------------------------------------------------------------------------------- 1 | #ifndef PROXY_HPP 2 | #define PROXY_HPP 3 | class Image { 4 | protected: 5 | int myId; 6 | Image() =default; 7 | ~Image() =default; 8 | virtual void draw() = 0; 9 | }; 10 | 11 | class RealImage : public Image { 12 | public: 13 | RealImage(int i) { myId = i; } 14 | 15 | void draw() { cout << " drawing image " << myId << '\n'; } 16 | }; 17 | 18 | class ProxyImage : public Image { 19 | RealImage* realImage; 20 | static int next; 21 | public: 22 | ProxyImage() { 23 | myId = next++; 24 | realImage = 0; 25 | } 26 | 27 | void draw() { 28 | if (!realImage) { 29 | realImage = new RealImage(myId); 30 | } 31 | realImage->draw(); 32 | } 33 | }; 34 | 35 | int ProxyImage::next = 1; 36 | 37 | #endif // PROXY_HPP 38 | -------------------------------------------------------------------------------- /facade.hpp: -------------------------------------------------------------------------------- 1 | #ifndef FACADE_HPP 2 | #define FACADE_HPP 3 | 4 | class Band { 5 | private: 6 | GuitarPlayer _GuitarPlayer; 7 | Drummer _Drummer; 8 | BassPlayer _BassPlayer; 9 | void PlayVerse(int nVerse); 10 | void PlayChorus(); 11 | void PlaySolo(); 12 | public: 13 | Band(const char *guitarPlayerName, const char *drummerName, 14 | const char *bassPlayerName) : _GuitarPlayer(guitarPlayerName), 15 | _Drummer(drummerName), _BassPlayer(bassPlayerName) { } 16 | ~Band() { } 17 | void PlaySong(); 18 | }; 19 | 20 | class Musician { 21 | protected: 22 | string _Name; 23 | public: 24 | virtual ~Musician() { } 25 | }; 26 | 27 | class GuitarPlayer: public Musician { 28 | public: 29 | GuitarPlayer(const char *name) { _Name = name; } 30 | ~GuitarPlayer() override { } 31 | void PlayVerseRiff(int nVerse); 32 | void PlayChorusRiff(); 33 | void PlaySolo(); 34 | }; 35 | 36 | #endif // FACADE_HPP 37 | -------------------------------------------------------------------------------- /object_adapter.hpp: -------------------------------------------------------------------------------- 1 | #ifndef OBJECT_ADAPTER_HPP 2 | #define OBJECT_ADAPTER_HPP 3 | 4 | class TextShape : public Shape { 5 | public: 6 | TextShape(TextView*); 7 | virtual void BoundingBox( Point& bottomLeft, Point& topRight) const; 8 | virtual bool IsEmpty() const; 9 | virtual Manipulator* CreateManipulator() const; 10 | private: 11 | TextView* _text; 12 | }; 13 | 14 | 15 | 16 | TextShape::TextShape (TextView* t) { 17 | _text = t; 18 | } 19 | 20 | 21 | void TextShape::BoundingBox (Point& bottomLeft, Point& topRight) const 22 | { 23 | Coord bottom, left, width, height; 24 | 25 | _text->GetOrigin(bottom, left); 26 | _text->GetExtent(width, height); 27 | 28 | bottomLeft = Point(bottom, left); 29 | topRight = Point(bottom + height, left + width); 30 | } 31 | 32 | 33 | bool TextShape::IsEmpty () const 34 | { 35 | return _text->IsEmpty(); 36 | } 37 | 38 | 39 | Manipulator* TextShape::CreateManipulator () const 40 | { 41 | return new TextManipulator(this); 42 | } 43 | 44 | #endif // OBJECT_ADAPTER_HPP 45 | -------------------------------------------------------------------------------- /decorator.hpp: -------------------------------------------------------------------------------- 1 | #ifndef DECORATOR_HPP 2 | #define DECORATOR_HPP 3 | #include 4 | using namespace std; 5 | class Widget // component 6 | { 7 | public: 8 | Widget(); 9 | virtual void draw(); 10 | 11 | }; 12 | 13 | class TextField: public Widget // conComponent 14 | { 15 | int width, height; 16 | public: 17 | TextField(int w, int h) { 18 | width = w; 19 | height = h; 20 | } 21 | void draw() { cout << "TextField: " << width << ", " << height << 'n'; } 22 | 23 | }; 24 | 25 | class Decorator: public Widget // Decorator 26 | { 27 | Widget *wid; 28 | public: 29 | Decorator(Widget *w) {wid = w;} 30 | void draw() {wid->draw();} 31 | }; 32 | 33 | class BorderDecorator: public Decorator // Decorator A 34 | { 35 | public: 36 | BorderDecorator(Widget *w): Decorator(w) {} 37 | void draw() {Decorator::draw();cout << "BorderDecorator" << 'n';} 38 | 39 | }; 40 | 41 | 42 | //Widget *aWidget = new BorderDecorator( new BorderDecorator( (new TextField(80, 24)))); 43 | //aWidget->draw(); 44 | #endif // DECORATOR_HPP 45 | -------------------------------------------------------------------------------- /factory_method.hpp: -------------------------------------------------------------------------------- 1 | #ifndef FACTORY_METHOD_HPP 2 | #define FACTORY_METHOD_HPP 3 | #include 4 | #include 5 | 6 | using namespace std; 7 | 8 | class Product { 9 | public: 10 | virtual string getName() = 0; 11 | virtual ~Product() {} 12 | }; 13 | 14 | class ConcreteProductA: public Product { 15 | public: 16 | string getName() {return "ConcreteProductA";} 17 | }; 18 | 19 | class ConcreteProductB: public Product { 20 | public: 21 | string getName() {return "ConcreteProductB";} 22 | }; 23 | 24 | class Creator { 25 | public: 26 | Product* GetProduct(); 27 | protected: 28 | virtual Product* CreateProduct() = 0; 29 | private: 30 | Product* prod = nullptr; 31 | }; 32 | 33 | template 34 | class ConcreteCreator : public Creator 35 | { 36 | protected: 37 | virtual Product* CreateProduct() 38 | { 39 | return new tprod; 40 | } 41 | 42 | }; 43 | 44 | Product* Creator::GetProduct() 45 | { 46 | if(prod == nullptr) 47 | prod = CreateProduct(); 48 | 49 | return prod; 50 | } 51 | #endif // FACTORY_METHOD_HPP 52 | -------------------------------------------------------------------------------- /flyweight.hpp: -------------------------------------------------------------------------------- 1 | #ifndef FLYWEIGHT_HPP 2 | #define FLYWEIGHT_HPP 3 | 4 | //работа с символами 5 | #include 6 | //базовый класс: 7 | class Character 8 | { 9 | protected: 10 | char Symbol; 11 | int Size; 12 | public: 13 | virtual void view() = 0; //если 0 не написать, то метод нужно будет реализовать хотя бы где-нибудь 14 | }; 15 | 16 | class CharacterFactory 17 | { 18 | private: 19 | std::map Characters; //связка ключ_символ - значение_ОбъектСимвола 20 | int size; 21 | public: 22 | Character& GetCharacter(char key) 23 | { 24 | /*std::map::iterator*/Characters::iterator it = Characters.find(key); 25 | if (Characters.end() == it) 26 | { 27 | Character* ch = new ConCharacter(key,size); 28 | Characters[key] = ch; 29 | return *ch; 30 | } 31 | else 32 | { 33 | return *it->second; //приспособленец или возвращает новый объект, или указатель на существующий 34 | } 35 | } 36 | }; 37 | 38 | 39 | #endif // FLYWEIGHT_HPP 40 | -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | MIT License 2 | 3 | Copyright (c) 2017 Pandas 4 | 5 | Permission is hereby granted, free of charge, to any person obtaining a copy 6 | of this software and associated documentation files (the "Software"), to deal 7 | in the Software without restriction, including without limitation the rights 8 | to use, copy, modify, merge, publish, distribute, sublicense, and/or sell 9 | copies of the Software, and to permit persons to whom the Software is 10 | furnished to do so, subject to the following conditions: 11 | 12 | The above copyright notice and this permission notice shall be included in all 13 | copies or substantial portions of the Software. 14 | 15 | THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 16 | IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 17 | FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE 18 | AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 19 | LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 20 | OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE 21 | SOFTWARE. 22 | -------------------------------------------------------------------------------- /class_adapter.hpp: -------------------------------------------------------------------------------- 1 | #ifndef ADAPTER_HPP 2 | #define ADAPTER_HPP 3 | 4 | class Shape { 5 | public: 6 | Shape(); 7 | virtual void BoundingBox(Point& bottomLeft, Point& topRight ) const; 8 | virtual Manipulator* CreateManipulator() const; 9 | }; 10 | 11 | 12 | class TextView { 13 | public: 14 | TextView(); 15 | void GetOrigin(Coord& x, Coord& y) const; 16 | void GetExtent(Coord& width, Coord& height) const; 17 | virtual bool IsEmpty() const; 18 | }; 19 | 20 | 21 | class TextShape : public Shape, private TextView { 22 | public: 23 | TextShape(); 24 | virtual void BoundingBox(Point& bottomLeft, Point& topRight) const; 25 | virtual bool IsEmpty() const; 26 | virtual Manipulator* CreateManipulator() const; 27 | }; 28 | 29 | void TextShape::BoundingBox (Point& bottomLeft, Point& topRight) const 30 | { 31 | Coord bottom, left, width, height; 32 | 33 | GetOrigin(bottom, left); 34 | GetExtent(width, height); 35 | 36 | bottomLeft = Point(bottom, left); 37 | topRight = Point(bottom + height, left + width); 38 | //.. 39 | } 40 | 41 | 42 | bool TextShape::IsEmpty () const 43 | { 44 | return TextView::IsEmpty(); 45 | } 46 | 47 | Manipulator* TextShape::CreateManipulator () const 48 | { 49 | return new TextManipulator(this); 50 | } 51 | 52 | #endif // ADAPTER_HPP 53 | -------------------------------------------------------------------------------- /adapter.hpp: -------------------------------------------------------------------------------- 1 | #ifndef ADAPTER_HPP 2 | #define ADAPTER_HPP 3 | 4 | // Я, кажись, так писала: 5 | 6 | class Shape { 7 | public: 8 | Shape(); 9 | virtual void BoundingBox(Point& bottomLeft, Point& topRight) const; 10 | virtual Manipulator* CreateManipulator() const; 11 | }; 12 | 13 | class TextView { 14 | public: 15 | TextView(); 16 | void GetOrigin(Coord& x, Coord& y) const; 17 | void GetExtent(Coord& width, Coord& height) const; 18 | virtual bool IsEmpty() const; 19 | }; 20 | 21 | class TextShape : public Shape { 22 | public: 23 | TextShape(TextView*); 24 | virtual void BoundingBox(Point& bottomLeft, Point& topRight) const; 25 | virtual bool IsEmpty() const; 26 | virtual Manipulator* CreateManipulator() const; 27 | private: 28 | TextView* _text; 29 | }; 30 | 31 | TextShape::TextShape (TextView* t) { 32 | _text = t; 33 | } 34 | 35 | void TextShape::BoundingBox (Point& bottomLeft, Point& topRight) const { 36 | Coord bottom, left, width, height; 37 | 38 | _text->GetOrigin(bottom, left); 39 | _text->GetExtent(width, height); 40 | 41 | bottomLeft = Point(bottom, left); 42 | topRight = Point(bottom + height, left + width); 43 | } 44 | 45 | bool TextShape::IsEmpty () const { 46 | return _text->IsEmpty(); 47 | } 48 | 49 | Manipulator* TextShape::CreateManipulator () const { 50 | return new TextManipulator(this); 51 | } 52 | 53 | #endif // ADAPTER_HPP 54 | -------------------------------------------------------------------------------- /pool.hpp: -------------------------------------------------------------------------------- 1 | #ifndef POOL_HPP 2 | #define POOL_HPP 3 | #include 4 | class Object 5 | { 6 | // ... 7 | }; 8 | 9 | class ObjectPool 10 | { 11 | private: 12 | struct PoolRecord 13 | { 14 | Object* instance; 15 | bool in_use; 16 | }; 17 | 18 | std::vector m_pool; 19 | public: 20 | Object* createNewObject() 21 | { 22 | for (size_t i = 0; i < m_pool.size(); ++i) 23 | { 24 | if (! m_pool[i].in_use) 25 | { 26 | m_pool[i].in_use = true; // переводим объект в список используемых 27 | return m_pool[i].instance; 28 | } 29 | } 30 | 31 | // если не нашли свободный объект, то расширяем пул 32 | PoolRecord record; 33 | record.instance = new Object; 34 | record.in_use = true; 35 | m_pool.push_back(record); 36 | return record.instance; 37 | 38 | } 39 | 40 | void deleteObject(Object* object) 41 | { 42 | // в реальности не удаляем, а лишь помечаем, что объкт свободен 43 | for (size_t i = 0; i < m_pool.size(); ++i) 44 | { 45 | if (m_pool[i].instance == object) 46 | { 47 | m_pool[i].in_use = false; 48 | break; 49 | } 50 | } 51 | } 52 | 53 | virtual ~ObjectPool() 54 | { 55 | // теперь уже "по-настоящему" удаляем объекты 56 | for (size_t i = 0; i < m_pool.size(); ++i) 57 | delete m_pool[i].instance; 58 | } 59 | }; 60 | #endif // POOL_HPP 61 | -------------------------------------------------------------------------------- /bridge.hpp: -------------------------------------------------------------------------------- 1 | #ifndef BRIDGE_HPP 2 | #define BRIDGE_HPP 3 | class Window { 4 | public: 5 | Window(View* contents); 6 | // запросы, обрабатываемые окном 7 | virtual void DrawContents(); 8 | virtual void Open(); 9 | virtual void Close(); 10 | virtual void Iconify(); 11 | virtual void Deiconify(); 12 | 13 | // запросы, перенаправляемые реализации 14 | virtual void SetOrigin(const Point& at); 15 | virtual void SetExtent(const Point& extent); 16 | virtual void Raise(); 17 | virtual void Lower(); 18 | 19 | virtual void DrawLine(const Point&, const Point&); 20 | virtual void DrawRect(const Point&, const Point&); 21 | virtual void DrawPolygon(const Point[], int n); 22 | virtual void DrawText(const char*, const Point&); 23 | protected: 24 | WindowImp* GetWindowImp(); 25 | View* GetView(); 26 | private: 27 | WindowImp* _imp; 28 | View* _contents; // содержимое окна 29 | }; 30 | 31 | class WindowImp { 32 | public: 33 | virtual void ImpTop() = 0; 34 | virtual void ImpBottom() = 0; 35 | virtual void ImpSetExtent(const Point&) = 0; 36 | virtual void ImpSetOrigin(const Point&) = 0; 37 | virtual void DeviceRect(Coord, Coord, Coord, Coord) = 0; 38 | virtual void DeviceText(const char*, Coord, Coord) = 0; 39 | virtual void DeviceBitmap(const char*, Coord, Coord) = 0; 40 | //.. 41 | protected: 42 | WindowImp(); 43 | }; 44 | 45 | WindowImp* Window::GetWindowImp () { 46 | if (_imp == 0) { 47 | _imp = WindowSystemFactory::Instance()->MakeWindowImp(); 48 | } 49 | return _imp; 50 | } 51 | 52 | class ApplicationWindow : public Window { 53 | public: 54 | // ... 55 | virtual void DrawContents(); 56 | }; 57 | 58 | void ApplicationWindow::DrawContents () { 59 | GetView()->DrawOn(this); 60 | } 61 | #endif // BRIDGE_HPP 62 | -------------------------------------------------------------------------------- /composite.hpp: -------------------------------------------------------------------------------- 1 | #ifndef COMPOSITE_CPP 2 | #define COMPOSITE_CPP 3 | 4 | class Equipment { 5 | public: 6 | virtual ~Equipment(); 7 | const char* Name() { return _name; } 8 | virtual Watt Power(); 9 | virtual Currency NetPrice(); virtual Currency DiscountPrice(); 10 | virtual void Add(Equipment*); 11 | virtual void Remove(Equipment*); 12 | virtual Iterator* CreateIterator(); 13 | protected: 14 | Equipment(const char*); 15 | private: 16 | const char* _name; 17 | }; 18 | 19 | 20 | class FloppyDisk : public Equipment { //leaf 21 | public: 22 | FloppyDisk(const char*); 23 | virtual ~FloppyDisk(); 24 | virtual Watt Power(); 25 | virtual Currency NetPrice(); 26 | virtual Currency DiscountPrice(); 27 | 28 | }; 29 | 30 | class CompositeEquipment : public Equipment { //composite 31 | public: 32 | virtual ~CompositeEquipment(); 33 | virtual Watt Power(); 34 | virtual Currency NetPrice(); 35 | virtual Currency DiscountPrice(); 36 | virtual void Add(Equipment*); 37 | virtual void Remove(Equipment*); 38 | virtual Iterator* CreateIterator(); 39 | protected: 40 | CompositeEquipment(const char*); 41 | private: 42 | List _equipment; 43 | }; 44 | 45 | 46 | 47 | class Chassis : public CompositeEquipment { 48 | public: 49 | Chassis(const char*); 50 | virtual ~Chassis(); 51 | virtual Watt Power(); 52 | virtual Currency NetPrice(); 53 | virtual Currency DiscountPrice(); 54 | }; 55 | 56 | Currency CompositeEquipment::NetPrice () { 57 | Iterator* i = CreateIterator(); 58 | Currency total = 0; 59 | 60 | for (i->First(); !i->IsDone(); i->Next()) { 61 | total += i->CurrentItem()->NetPrice(); 62 | } 63 | delete i; 64 | return total; 65 | } 66 | #endif // COMPOSITE_CPP 67 | -------------------------------------------------------------------------------- /mediator.hpp: -------------------------------------------------------------------------------- 1 | #ifndef MEDIATOR_HPP 2 | #define MEDIATOR_HPP 3 | #include 4 | #include 5 | class Colleague; 6 | class Mediator; 7 | class ConcreteMediator; 8 | class ConcreteColleague1; 9 | class ConcreteColleague2; 10 | 11 | class Mediator { 12 | public: 13 | virtual void Send(std::string const& message, Colleague *colleague) const = 0; 14 | }; 15 | 16 | 17 | class Colleague { 18 | protected: 19 | Mediator* mediator_; 20 | public: 21 | explicit Colleague(Mediator *mediator):mediator_(mediator) {} 22 | }; 23 | 24 | class ConcreteColleague1:public Colleague { 25 | public: 26 | explicit ConcreteColleague1(Mediator* mediator):Colleague(mediator) {} 27 | void Send(std::string const& message) { 28 | mediator_->Send(message, this); 29 | } 30 | void Notify(std::string const& message) { 31 | std::cout << "Colleague1 gets message '" << message << "'" << std::endl; 32 | } 33 | }; 34 | 35 | class ConcreteColleague2:public Colleague { 36 | public: 37 | explicit ConcreteColleague2(Mediator *mediator):Colleague(mediator) {} 38 | void Send(std::string const& message) { 39 | mediator_->Send(message, this); 40 | } 41 | void Notify(std::string const& message) { 42 | std::cout << "Colleague2 gets message '" << message << "'" << std::endl; 43 | } 44 | }; 45 | 46 | class ConcreteMediator:public Mediator { 47 | protected: 48 | ConcreteColleague1 *m_Colleague1; 49 | ConcreteColleague2 *m_Colleague2; 50 | public: 51 | void SetColleague1(ConcreteColleague1 *c) { 52 | m_Colleague1=c; 53 | } 54 | void SetColleague2(ConcreteColleague2 *c) { 55 | m_Colleague2=c; 56 | } 57 | virtual void Send(std::string const& message, Colleague *colleague) const 58 | { 59 | if (colleague==m_Colleague1) 60 | { 61 | m_Colleague2->Notify(message); 62 | } 63 | else if (colleague==m_Colleague2) 64 | { 65 | m_Colleague1->Notify(message); 66 | } 67 | } 68 | }; 69 | 70 | /* 71 | ConcreteMediator m; 72 | ConcreteColleague1 c1(&m); 73 | ConcreteColleague2 c2(&m); 74 | m.SetColleague1(&c1); 75 | m.SetColleague2(&c2); 76 | c1.Send( ); 77 | c2.Send( ); 78 | std::cin.get(); 79 | return 0;*/ 80 | #endif // MEDIATOR_HPP 81 | -------------------------------------------------------------------------------- /holder.hpp: -------------------------------------------------------------------------------- 1 | #ifndef HOLDER_HPP 2 | #define HOLDER_HPP 3 | using namespace std; 4 | 5 | template 6 | class Holder; 7 | 8 | template 9 | class Trule //TRansfer capsULE //используется только для передачи; чтобы при передачи в метод функции или возврата функции из метода, не возникло утечки 10 | { 11 | private: 12 | T* ptr; 13 | public: 14 | Trule(Holder&h) 15 | { 16 | ptr = h.release(); 17 | } 18 | ~Trule() //при передаче параметров также возможна отработка исключений; необходимо позаботиться об уничтожении труля 19 | { 20 | delete ptr; 21 | } 22 | private: 23 | Trule(Trule&); 24 | Trule& operator = (Trule&); 25 | friend class Holder; //для простоты обращения 26 | }; 27 | 28 | template 29 | class Holder 30 | { 31 | private: 32 | T* ptr; 33 | public: 34 | Holder(): ptr(0) {} //когда создаётся холдер указателя, он не должен принимать указатель откуда-то извне - это может привести к тому, что холдер может держать указатель на уже освобождённую память 35 | explicit Holder(T* p): ptr(p) {} //нужен явный вызов конструктора, явное создание объекта 36 | ~Holder() 37 | { 38 | delete ptr; 39 | } 40 | //холдер должен быть прозрачен: черзе него мы должны мочь обратиться ко всему что он держит 41 | T* operator ->() const 42 | {return ptr;} 43 | 44 | //также нужна и работа со ссылкой на объект 45 | T& opetator *() const {return *ptr;} 46 | 47 | //обмен 48 | void exchange(Holder& h) 49 | { 50 | swap(ptr, h.ptr); } 51 | 52 | } 53 | //холдер берёт на себя указатель капсулы 54 | Holder(Trule const& t) 55 | { 56 | ptr = t.ptr; 57 | //т.птр - константа, поэтому приходится извращаться 58 | const_cast&>(t).ptr = 0; 59 | } 60 | 61 | //присваивание 62 | Holder& operator = (Trule const& t) 63 | { 64 | delete ptr; 65 | ptr = t.ptr; 66 | const_cast&>(t).ptr = 0; 67 | return *this; 68 | } 69 | T* release() 70 | { 71 | T* p = ptr; 72 | ptr = 0; 73 | return p; 74 | } 75 | //также нужны ещё конструктор копирования и оператор присванивания(холдер холдер) 76 | //при передаче объектов в функцию мы будем использовать трул 77 | }; 78 | 79 | #endif // HOLDER_HPP 80 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # Design Patterns and Containers 2 | 3 | 4 | 2nd course, 4th semester 5 | 6 | Bauman Moscow State Technical University 7 | 8 | ### Creational patterns 9 | 10 | | Pattern | Description | Implementation | 11 | | ------------- |:-------------:|:-------------:| 12 | |[Abstract Factory](../../wiki/Abstract-Factory)| ✅ |✅ | 13 | |[Builder](https://github.com/Panda-Lewandowski/Design-Patterns/wiki/Builder)| ✅ |✅| 14 | |[Factory Method](https://github.com/Panda-Lewandowski/Design-Patterns/wiki/Factory-Method)|✅|✅| 15 | |[Prototype](https://github.com/Panda-Lewandowski/Design-Patterns/wiki/Prototype)|✅|✅| 16 | |[Singleton](https://github.com/Panda-Lewandowski/Design-Patterns/wiki/Singleton)|✅|✅| 17 | |[Pool](https://github.com/Panda-Lewandowski/Design-Patterns/wiki/Pool)|✅|✅| 18 | 19 | ### Structural pattern 20 | 21 | | Pattern | Description | Implementation | 22 | | ------------- |:-------------:|:-------------:| 23 | |[Adapter](../../wiki/Adapter)|✅|✅| 24 | |[Bridge](../../wiki/Bridge)|✅|✅| 25 | |[Composite](../../wiki/Composite)|✅|✅| 26 | |[Decorator](../../wiki/Decorator)|✅|✅| 27 | |[Facade](../../wiki/Facade)|✅|✅| 28 | |[Proxy](../../wiki/Proxy)|✅|✅| 29 | |[Flyweight](../../wiki/Flyweight)|✅|✅| 30 | 31 | ### Behavioral patterns 32 | 33 | | Pattern | Description | Implementation | 34 | | ------------- |:-------------:|:-------------:| 35 | |[Chain of Responsibility](../../wiki/Chain-of-Responsibility)|✅|✅| 36 | |[Command](../../wiki/Command)|✅|✅| 37 | |[Mediator](../../wiki/Mediator)|✅|✅| 38 | |[Holder](../../wiki/Holder)(NOT Memento)|✅|✅| 39 | |[Observer](../../wiki/Observer)|✅|🌀| 40 | |[State](../../wiki/State)|✅|⚠️| 41 | |[Strategy](../../wiki/Strategy)|✅|⚠️| 42 | |[Template Method](../../wiki/Template-Method)|✅|⚠️| 43 | |[Visitor](../../wiki/Visitor)|✅|⚠️| 44 | |[Interpreter](../../wiki/Interpreter)|✅|⚠️| 45 | |[Iterator](../../wiki/Iterator)|✅|⚠️| 46 | 47 | ### Containers 48 | 49 | | Container | Implementation | 50 | | ------------- |:-------------:| 51 | |Arraay|| 52 | |Iterator|| 53 | |Vector|| 54 | |Set|| 55 | |List|| 56 | |Matrix|| 57 | 58 | #### Materials: 59 | |Link|Type|Language| 60 | |-------------|:-------------:|:-------------:| 61 | |[Design Patterns](https://vk.com/videos-54530371?section=album_56085788)|:vhs:|🇷🇺| 62 | |[Design Patterns: Elements of Reusable Object-Oriented Software](https://en.wikipedia.org/wiki/Design_Patterns)| :book: |🇷🇺 :uk: etc| 63 | 64 | 65 | #### Legend: 66 |
    67 |
  • ✅ - ОК 68 |
  • ⚠️ - problem 69 |
  • 🆘 - need help 70 |
  • 🌀 - in process 71 |
  • :vhs: - video 72 |
  • 🇷🇺 - Russian language 73 |
74 | 75 | -------------------------------------------------------------------------------- /observer.hpp: -------------------------------------------------------------------------------- 1 | #ifndef OBSERVER_HPP 2 | #define OBSERVER_HPP 3 | delegate void EventHandler(Object^ source, double a); 4 | 5 | public ref class Manager //издатель 6 | { 7 | public: 8 | event EventHandler^ OnHandler; 9 | void method() 10 | { 11 | OnHandler(this, 10.); 12 | } 13 | } 14 | public ref class Watcher //подписчик 15 | { 16 | public: 17 | Watcher(Manager^ m) 18 | { 19 | m->OnHandler += gcnew EventHandler(this, &Watcher::f) //& - потомучто метод класса 20 | } 21 | void f(Object^ source, double a) //подписали метод f на возникновение события. Когда начнёт выполняться method, будут выполняться методы классов, подписанных на возникновение события 22 | { 23 | //... 24 | } 25 | } 26 | } 27 | #endif // OBSERVER_HPP 28 | 29 | 30 | /* 31 | ref - память распределяется только динамически под объект 32 | ^ - замена * - ук-ль на управляемую кучу 33 | += - т.к. на 1 событие можно подписываться много раз 34 | */ 35 | 36 | 37 | class lift 38 | { 39 | int floor; // текущий этаж 40 | doors* door; 41 | public: 42 | lift(); //конструктор лифта 43 | 44 | public slots: 45 | void go_up(); //топать вверх 46 | void go_down(); //топать вниз 47 | void open_doors(); //открыть двери 48 | void close_doors(); //закрыть двери 49 | void wait_here(); //ждать столько то секунд 50 | 51 | signals: 52 | void opening_doors(); 53 | void closing_doors(); 54 | void arrived(); //приехал 55 | void up(); //едет вверх 56 | void down(); //едет вниз 57 | }; 58 | 59 | 60 | class doors 61 | { 62 | public: 63 | doors(); //конструктор дверей 64 | 65 | public slots: 66 | void open(); //открыть 67 | void close(); //закрыть 68 | void start_open(); //начать открывать 69 | void start_close(); //начать закрывать 70 | 71 | signals: 72 | void opening(); //двери открыты 73 | void closing(); //двери закрыты 74 | 75 | }; 76 | 77 | doors::doors() 78 | { 79 | connect(this, SIGNAL(opening()), this, SLOT(start_open())); 80 | connect(this, SIGNAL(closing()), this, SLOT(start_close())); 81 | 82 | } 83 | 84 | 85 | lift::lift() 86 | { 87 | this->floor = 1; 88 | this->door = new doors; 89 | connect(this, SIGNAL(arrived()), this->door, SLOT(open())); 90 | connect(this, SIGNAL(opening_doors()), this, SLOT(open_doors())); 91 | connect(this, SIGNAL(closing_doors()), this, SLOT(close_doors())); 92 | connect(this, SIGNAL(up()), this, SLOT(go_up())); 93 | connect(this, SIGNAL(down()), this, SLOT(go_down())); 94 | connect(this, SIGNAL(up()), this->door, SLOT(close())); 95 | connect(this, SIGNAL(down()), this->door, SLOT(close())); 96 | 97 | } 98 | 99 | void lift::open_doors() 100 | { 101 | emit this->door->opening(); 102 | } 103 | 104 | 105 | void lift::close_doors() 106 | { 107 | emit this->door->closing(); 108 | } 109 | -------------------------------------------------------------------------------- /chain_of_responsibility.hpp: -------------------------------------------------------------------------------- 1 | #ifndef CHAIN_OF_RESPONSIBILITY_HPP 2 | #define CHAIN_OF_RESPONSIBILITY_HPP 3 | #include 4 | /** 5 | * Вспомогательный класс, описывающий некоторое преступление */ 6 | class CriminalAction { 7 | friend class Policeman; 8 | int complexity; 9 | const char* description; 10 | public: 11 | // Полицейские имеют доступ к материалам следствия // Сложность дела 12 | // Краткое описание преступления 13 | CriminalAction(int complexity, const char* description): complexity(complexity), description(description) {} 14 | }; 15 | 16 | 17 | /** 18 | * Абстрактный полицейский, который может заниматься расследованием преступлений */ 19 | class Policeman { 20 | protected: 21 | int deduction; // дедукция (умение распутывать сложные дела) у данного полицейского 22 | Policeman* next; // более умелый полицейский, который получит дело, если для текущего оно слишком сложное 23 | virtual void investigateConcrete(const char* description) {} // собственно расследование 24 | public: 25 | Policeman(int deduction): deduction(deduction) {} 26 | virtual ~Policeman() { if (next) { delete next; }} 27 | /* 28 | * Добавляет в цепочку ответственности более опытного полицейского, который сможет 29 | принять на себя 30 | * расследование, если текущий не справится 31 | */ 32 | Policeman* setNext(Policeman* policeman) { 33 | next = policeman; 34 | return next; 35 | } 36 | 37 | /* 38 | * Полицейский начинает расследование или, если дело слишком сложное, передает ее 39 | более опытному коллеге */ 40 | void investigate(CriminalAction* criminalAction) 41 | { 42 | if (deduction < criminalAction->complexity) 43 | { 44 | if (next) 45 | { 46 | next->investigate(criminalAction); 47 | } 48 | else 49 | { 50 | std::cout << "Это дело не раскрыть никому." << std::endl; 51 | } 52 | } 53 | else 54 | { 55 | investigateConcrete(criminalAction->description); 56 | } 57 | } 58 | }; 59 | 60 | 61 | class MartinRiggs: public Policeman { 62 | protected: 63 | void investigateConcrete(const char* description) { 64 | std::cout << "Расследование по делу \"" << description << "\" ведет сержант Мартин Риггс"<< std::endl; 65 | } 66 | public: 67 | MartinRiggs(int deduction): Policeman(deduction) {} 68 | 69 | }; 70 | 71 | class JohnMcClane: public Policeman { 72 | protected: 73 | void investigateConcrete(const char* description) { 74 | std::cout << "Расследование по делу \"" << description << "\" ведет детектив Джон Макклейн" << std::endl; 75 | } 76 | public: 77 | JohnMcClane(int deduction): Policeman(deduction) {} 78 | }; 79 | 80 | class VincentHanna: public Policeman { 81 | protected: 82 | void investigateConcrete(const char* description) { 83 | std::cout << "Расследование по делу \"" << description << "\" ведет лейтенант Винсент Ханна" << std::endl; 84 | } 85 | public: 86 | VincentHanna(int deduction): Policeman(deduction) {} 87 | }; 88 | 89 | 90 | #endif // CHAIN_OF_RESPONSIBILITY_HPP 91 | -------------------------------------------------------------------------------- /vector.hpp: -------------------------------------------------------------------------------- 1 | #ifndef VECTOR_HPP 2 | #define VECTOR_HPP 3 | #include "Errors.h" 4 | #include 5 | using std::istream; 6 | using std::ostream; 7 | class ArrayBase { 8 | public: 9 | ArrayBase () { } 10 | virtual ~ArrayBase () { } 11 | 12 | int getsize() const { 13 | return _size; 14 | } 15 | 16 | 17 | protected: 18 | int _size; 19 | static const int DefaultSize = 20; 20 | }; 21 | 22 | 23 | template 24 | class ArrayT : public ArrayBase { 25 | public: 26 | 27 | // онструкторы 28 | ArrayT ( int n = DefaultSize ); 29 | ArrayT ( const T*, int sz ); 30 | ArrayT ( const ArrayT& ); 31 | 32 | // ƒеструктор 33 | ~ArrayT ( ); 34 | 35 | // опирование массива 36 | ArrayT& operator= ( const ArrayT& ); 37 | 38 | // ѕерегрузка операторов сравнени€ 39 | bool operator == ( const ArrayT& ) const; 40 | bool operator != ( const ArrayT& ) const; 41 | static bool is_equal ( const ArrayT&, const ArrayT& ); 42 | 43 | // ќбъединение массивов 44 | static ArrayT& concat( const ArrayT&, const ArrayT&); 45 | 46 | // ”меньшение длины массива 47 | static ArrayT& split_array ( const ArrayT&, int pos, int num ); 48 | 49 | // ѕрибавление одного и того же числа ко всем элементам массива 50 | ArrayT& operator += ( const T& ); 51 | ArrayT& add_value ( const T& ); 52 | ArrayT& operator -= ( const T& ); 53 | ArrayT& subst_value ( const T& ); 54 | 55 | // ”множение всех элементов массива на одно и то же число 56 | ArrayT& operator *= ( const T& ); 57 | ArrayT& operator /= ( const T& ); 58 | ArrayT& mult_value ( const T& ); 59 | ArrayT& div_value ( const T& ); 60 | 61 | // —ложение массивов 62 | ArrayT& operator += ( const ArrayT& ); 63 | ArrayT& add_array ( const ArrayT& ); 64 | 65 | // ¬ычитание массивов 66 | ArrayT& operator -= ( const ArrayT& ); 67 | ArrayT& subst_array ( const ArrayT& ); 68 | 69 | // —ортировка массива 70 | void QuickSortArr ( ); 71 | void QuickSortArr ( int st, int en ); 72 | 73 | // ѕерегрузка оператора [] 74 | T& operator [] ( int n ) { 75 | if (n<_size) 76 | return _arr[n]; 77 | else 78 | throw RangeError(1); 79 | }; 80 | const T& operator [] ( int n ) const { 81 | if (n<_size) 82 | return _arr[n]; 83 | else 84 | throw RangeError(1); 85 | }; 86 | 87 | // ѕоиск элементов в массиве 88 | T arr_min( int& ); 89 | T arr_max( int& ); 90 | int FindEl( T ); 91 | 92 | 93 | // ќбмен 94 | void arr_swap( int, int ); 95 | 96 | 97 | // ѕерегрузка потоков ввода-вывода 98 | template 99 | friend istream& operator >> ( istream&, ArrayT& ); 100 | template 101 | friend ostream& operator << ( ostream&, ArrayT& ); 102 | 103 | 104 | private: 105 | T* _arr; 106 | void arr_resize( int ); 107 | }; 108 | template 109 | istream& operator >> ( istream&, ArrayT& ); 110 | template 111 | ostream& operator << ( ostream&, ArrayT& ); 112 | 113 | 114 | #endif // VECTOR_HPP 115 | -------------------------------------------------------------------------------- /abstract_factory.hpp: -------------------------------------------------------------------------------- 1 | #ifndef ABSTRACT_FACTORY_HPP 2 | #define ABSTRACT_FACTORY_HPP 3 | #include 4 | #include 5 | 6 | using namespace std; 7 | 8 | // Абстрактные базовые классы графических примитивов 9 | class Ellipse 10 | { 11 | public: 12 | virtual void info() = 0; 13 | virtual ~Ellipse() {} 14 | }; 15 | 16 | class Line 17 | { 18 | public: 19 | virtual void info() = 0; 20 | virtual ~Line() {} 21 | }; 22 | 23 | class Polygon 24 | { 25 | public: 26 | virtual void info() = 0; 27 | virtual ~Polygon() {} 28 | }; 29 | 30 | // Классы граф. примитивов для двух разных библиотек 31 | class EllipseA: public Ellipse 32 | { 33 | public: 34 | void info() { 35 | cout << "Ellipse from lib A" << endl; 36 | } 37 | }; 38 | 39 | class LineA: public Line { 40 | public: 41 | void info() { 42 | cout << "Line from lib A" << endl; 43 | } 44 | }; 45 | 46 | class PolygonA: public Polygon { 47 | public: 48 | void info() { 49 | cout << "Polygon from lib A" << endl; 50 | } 51 | }; 52 | 53 | class EllipseB: public Ellipse 54 | { 55 | public: 56 | void info() { 57 | cout << "Ellipse from lib B" << endl; 58 | } 59 | }; 60 | 61 | class LineB: public Line { 62 | public: 63 | void info() { 64 | cout << "Line from lib B" << endl; 65 | } 66 | }; 67 | 68 | class PolygonB: public Polygon { 69 | public: 70 | void info() { 71 | cout << "Polygon from lib B" << endl; 72 | } 73 | }; 74 | 75 | 76 | // Абстрактная фабрика для производства примитивов 77 | class GrafFactory 78 | { 79 | public: 80 | virtual Ellipse* createEllipse() = 0; 81 | virtual Line* createLine() = 0; 82 | virtual Polygon* createPolygon() = 0; 83 | virtual ~GrafFactory() {} 84 | }; 85 | 86 | // Фабрика для создания воинов Римской армии 87 | class GrafAFactory: public GrafFactory 88 | { 89 | public: 90 | Ellipse* createEllipse() {return new EllipseA; } 91 | Line* createLine() {return new LineA; } 92 | Polygon* createPolygon() {return new PolygonA; } 93 | }; 94 | 95 | // Фабрика для создания воинов армии Карфагена 96 | class GrafBFactory: public GrafFactory 97 | { 98 | public: 99 | Ellipse* createEllipse() {return new EllipseB; } 100 | Line* createLine() {return new LineB; } 101 | Polygon* createPolygon() {return new PolygonB; } 102 | }; 103 | 104 | // Класс, содержащий всех воинов той или иной армии 105 | class Graf { 106 | public: 107 | ~Graf() { 108 | size_t i; 109 | for(i=0; iinfo(); 116 | for(i=0; iinfo(); 117 | for(i=0; iinfo(); 118 | } 119 | vector vi; 120 | vector va; 121 | vector vh; 122 | }; 123 | 124 | // Здесь создается армия той или иной стороны 125 | class Scene 126 | { 127 | public: 128 | Graf* createGraf( GrafFactory& factory ) { 129 | Graf* p = new Graf; 130 | p->vi.push_back( factory.createEllipse()); 131 | p->va.push_back( factory.createLine()); 132 | p->vh.push_back( factory.createPolygon()); 133 | return p; 134 | } 135 | }; 136 | 137 | #endif // ABSTRACT_FACTORY_HPP 138 | -------------------------------------------------------------------------------- /set.hpp: -------------------------------------------------------------------------------- 1 | #ifndef SET_TXT 2 | #define SET_TXT 3 | 4 | #include "Exceptions.h" 5 | #include "SetIterator.h" 6 | #include 7 | 8 | namespace myset 9 | { 10 | 11 | class BasicSet 12 | { 13 | public: 14 | bool isEmpty() const {return len==0;} 15 | int cardinality() const {return len;} 16 | BasicSet(int n = 0) : len(n) {} 17 | //virtual ~BasicSet(); 18 | protected: 19 | int len; 20 | }; 21 | 22 | template 23 | class Set: public BasicSet 24 | { 25 | public: 26 | Set(); 27 | Set(int n); 28 | Set(T *start, T *finish); 29 | Set(Set const& ob2); 30 | ~Set(); 31 | 32 | Set& operator=(Set const& ob2); 33 | void clear(); 34 | 35 | // функци€ сравнени€ элементов типа “ 36 | typedef bool (*FnCmp)(T const &element1, T const &element2); 37 | FnCmp compare; 38 | 39 | // —равнение множеств 40 | bool operator ==(Set const& ob2); 41 | bool operator !=(Set const& ob2); 42 | 43 | // ѕринадлежность множеству 44 | bool has(T const &element); 45 | bool operator >(T const &element); 46 | 47 | // ƒобавить элемент 48 | Set& operator +=(T const &element); 49 | Set operator +(T const &element) const; 50 | void addToSet(T const &element); 51 | 52 | // ”далить элемент 53 | Set& operator -=(T const &element); 54 | Set operator -(T const &element) const; 55 | void removeFromSet(T const &element); 56 | 57 | // ќбъединение 58 | Set& operator +=(Set const& ob2); 59 | Set operator +(Set const& ob2) const; 60 | 61 | // ѕересечение 62 | Set& operator *=(Set const& ob2); 63 | Set operator *(Set const& ob2) const; 64 | 65 | // –азность 66 | Set& operator -=(Set const& ob2); 67 | Set operator -(Set const& ob2) const; 68 | 69 | // —имметрическа€ разность 70 | Set& operator %=(Set const& ob2); 71 | Set operator %(Set const& ob2) const; 72 | 73 | // »тераторы 74 | typedef myset::SetIterator iterator; 75 | iterator begin() {T *temp = elements; return temp;} 76 | iterator end() {T *temp = elements; return temp+len-1;} 77 | private: 78 | static const int sizeOfSegment=50; 79 | T *elements; 80 | int find(T element) const; 81 | void checkMemory(); 82 | void constructor(int n); 83 | }; 84 | 85 | template 86 | Set unionOfSets(Set const& ob1, Set const& ob2) 87 | { 88 | return ob1+ob2; 89 | } 90 | 91 | template 92 | Set intersectionOfSets(Set const& ob1, Set const& ob2) 93 | { 94 | return ob1*ob2; 95 | } 96 | 97 | template 98 | Set differenceOfSets(Set const& ob1, Set const& ob2) 99 | { 100 | return ob1-ob2; 101 | } 102 | 103 | template 104 | Set symmetricDifferenceOfSets(Set const& ob1, Set const& ob2) 105 | { 106 | return ob1 % ob2; 107 | } 108 | 109 | template 110 | istream& operator>> (istream &in, Set &ob) 111 | { 112 | T temp; 113 | 114 | if (in) 115 | { 116 | in>>temp; 117 | ob += temp; 118 | } 119 | return in; 120 | } 121 | 122 | template 123 | ostream& operator<< (ostream &out, Set &ob) 124 | { 125 | for(Set::iterator it = ob.begin(); it!= ob.end(); ++it) 126 | out< 132 | bool defaultFnCompare(T const &element1, T const &element2) 133 | { 134 | return element1 == element2; 135 | } 136 | 137 | #endif // SET_TXT 138 | -------------------------------------------------------------------------------- /array.hpp: -------------------------------------------------------------------------------- 1 | #ifndef ARRAY_HPP 2 | #define ARRAY_HPP 3 | class BaseArray 4 | { 5 | public: 6 | BaseArray(){} 7 | virtual ~BaseArray(){} 8 | }; 9 | 10 | template 11 | class Array: public BaseArray 12 | { 13 | private: 14 | int capacity; 15 | int length; 16 | T** array; 17 | 18 | public: 19 | Array(); 20 | Array(int); 21 | Array(const Array &); 22 | ~Array(); 23 | 24 | void Show() const; 25 | int Length() const; 26 | int Search(const T&) const; 27 | void Add(const T&); 28 | void Del(int); 29 | T& operator [] (int) const; 30 | T** Resize(int); 31 | }; 32 | template 33 | Array::Array() 34 | { 35 | if( (array = (T**)calloc(FIRST_SIZE, sizeof(T*))) == NULL ) 36 | throw MemoryError(0); 37 | 38 | capacity = FIRST_SIZE; 39 | length = 0; 40 | } 41 | 42 | //------------------------------------------------------------- 43 | template 44 | Array::Array(int size) 45 | { 46 | if( (array = (T**)calloc(size, sizeof(T*))) == NULL ) 47 | throw MemoryError(0); 48 | 49 | capacity = size; 50 | length = 0; 51 | } 52 | 53 | //------------------------------------------------------------- 54 | 55 | template 56 | Array::Array(const Array& elem_arr) 57 | { 58 | if( (array = (T**)calloc(elem_arr.capacity, sizeof(T*))) == NULL ) 59 | throw MemoryError(0); 60 | 61 | length = elem_arr.Length(); 62 | capacity = elem_arr.capacity; 63 | 64 | for(int i = 0; i < length; i++) 65 | array[i] = new T(elem_arr[i]); 66 | } 67 | 68 | //------------------------------------------------------------- 69 | 70 | template 71 | Array::~Array() 72 | { 73 | for (int i = 0; i < length; i++) 74 | free(array[i]); 75 | free(array); 76 | } 77 | 78 | //------------------------------------------------------------- 79 | 80 | template 81 | void Array::Show() const 82 | { 83 | for(int i = 0; i < length; i++) 84 | { 85 | cout << *array[i] << " "; 86 | } 87 | cout << endl; 88 | } 89 | 90 | //------------------------------------------------------------- 91 | 92 | template 93 | int Array::Length() const 94 | { 95 | return length; 96 | } 97 | 98 | //------------------------------------------------------------- 99 | 100 | template 101 | T** Array::Resize(int size) 102 | { 103 | if( (array = (T**)realloc(array, sizeof(T*)*size)) == NULL ) 104 | throw MemoryError(0); 105 | capacity = size; 106 | 107 | return array; 108 | } 109 | 110 | //------------------------------------------------------------- 111 | 112 | template 113 | void Array::Add(const T& elem) 114 | { 115 | if (length == capacity) 116 | array = Resize(capacity + ADD_MEM); 117 | 118 | array[length++] = new T(elem); 119 | } 120 | 121 | //------------------------------------------------------------- 122 | 123 | template 124 | int Array::Search(const T& elem) const 125 | { 126 | int i; 127 | for (i = 0; i < length && *array[i] != elem; i++); 128 | 129 | return i < length ? i : NO_RESULTS; 130 | } 131 | 132 | //------------------------------------------------------------- 133 | 134 | template 135 | void Array::Del(int Pos) 136 | { 137 | if(Pos < 0 || Pos >= length) 138 | throw RangeError(Pos); 139 | 140 | length--; 141 | T temp = array[Pos]; 142 | 143 | array[Pos] = array[length]; 144 | delete temp; 145 | } 146 | 147 | //------------------------------------------------------------- 148 | 149 | template 150 | T& Array::operator [] (int Pos) const 151 | { 152 | if(Pos < 0 || Pos >= length) 153 | throw RangeError(Pos); 154 | 155 | return *array[Pos]; 156 | } 157 | 158 | #endif // ARRAY_HPP 159 | -------------------------------------------------------------------------------- /list.hpp: -------------------------------------------------------------------------------- 1 | #ifndef LIST_HPP 2 | #define LIST_HPP 3 | #include "Exeptions.h" 4 | #include "ListIterator.h" 5 | 6 | 7 | namespace List_model 8 | { 9 | template 10 | struct ListElem 11 | { 12 | T value; 13 | ListElem *next; 14 | ListElem *prev; 15 | }; 16 | 17 | class ListBase 18 | { 19 | public: 20 | bool is_empty() const {return size>0 ? false:true;} 21 | int get_size() const {return size;} 22 | ListBase(int n = 0): size(n) {} 23 | virtual ~ListBase() = 0{} 24 | protected: 25 | int size; 26 | }; 27 | 28 | template 29 | class List: public ListBase 30 | { 31 | public: 32 | typedef ListIterator iterator; 33 | public: 34 | List(): ListBase(), head(nullptr), tail(nullptr) {} 35 | List(T * arr, int n); 36 | List(const List &old_list); 37 | ~List(); 38 | T get(int n) const; 39 | T get_head() const {if is_empty() throw EmptyListAccessExeption("get_head"); return head->value;} 40 | T get_end() const {if is_empty() throw EmptyListAccessExeption("get_end");ListElem *wrk = head; while(wrk->next != nullptr) wrk = wrk->next; return wrk->value;} 41 | void set(T const& new_value, int n); 42 | void push_end(T const& value); 43 | void push_begin(T const& value); 44 | void push_after(T const& value, int n); 45 | T delete_begin(); 46 | T delete_index(int n); 47 | T delete_end(); 48 | iterator begin() {return head;} 49 | iterator end() {return tail;} 50 | void clear(); 51 | void swap(int n1, int n2); 52 | void sort(); 53 | void show(); 54 | int find(T const& value); 55 | List operator + (List &obj); 56 | List operator = (List &obj); 57 | private: 58 | ListElem *head, *tail; 59 | }; 60 | 61 | template 62 | istream& operator>> (istream &is, List &lst) 63 | { 64 | T temp; 65 | lst.clear(); 66 | while(is.good()) 67 | { 68 | is>>temp; 69 | lst.push_end(temp); 70 | } 71 | return is; 72 | } 73 | 74 | template 75 | ostream& operator<< (ostream &os, List &lst) 76 | { 77 | for(List::iterator it = lst.begin(); it!=nullptr; ++it) 78 | os< 85 | List::List(T * arr, int n) 86 | { 87 | ListElem *prev, *cur; 88 | if (!(head = new(std::nothrow) ListElem)) 89 | throw OutOfMemoryListExeption("constructor"); 90 | head->value = arr[0]; 91 | head->next = nullptr; 92 | head->prev = nullptr; 93 | size = 1; 94 | prev = head; 95 | for (int i = 1; i)) 98 | { 99 | this->~List(); 100 | throw OutOfMemoryListExeption("constructor"); 101 | } 102 | cur->value = arr[i]; 103 | cur->next = nullptr; 104 | cur->prev = prev; 105 | prev->next = cur; 106 | prev = cur; 107 | ++size; 108 | } 109 | tail = cur; 110 | } 111 | 112 | template 113 | List::List(const List &old_list) 114 | { 115 | if (old_list.is_empty()) 116 | { 117 | head = nullptr; 118 | tail = nullptr; 119 | size = 0; 120 | } 121 | else 122 | { 123 | ListElem *prev, *cur; 124 | if (!(head = new(std::nothrow) ListElem)) 125 | throw OutOfMemoryListExeption("constructor"); 126 | head->value = old_list.get(0); 127 | head->next = nullptr; 128 | head->prev = nullptr; 129 | size = 1; 130 | prev = head; 131 | for(int i = 1; i)) 134 | throw OutOfMemoryListExeption("constructor"); 135 | cur->value = old_list.get(i); 136 | cur->next = nullptr; 137 | cur->prev = prev; 138 | prev->next = cur; 139 | prev = cur; 140 | } 141 | tail = cur; 142 | size = old_list.get_size(); 143 | } 144 | } 145 | 146 | template 147 | List::~List() 148 | { 149 | ListElem *wrk; 150 | while(head != nullptr) 151 | { 152 | wrk = head->next; 153 | delete head; 154 | head = wrk; 155 | } 156 | } 157 | 158 | template 159 | T List::get(int n) const 160 | { 161 | if (is_empty()) 162 | throw EmptyListAccessExeption("get"); 163 | if((n>=0)&&(n *wrk = head; 166 | for(int i = 0; inext; 168 | return wrk->value; 169 | } 170 | else 171 | throw OutOfRangeListExeption("get"); 172 | } 173 | 174 | template 175 | void List::set(T const& new_value, int n) 176 | { 177 | if((n<0)||(n>size)) 178 | throw OutOfRangeListExeption("set"); 179 | ListElem *wrk = head; 180 | for(int i = 0; inext; 182 | wrk->value = new_value; 183 | } 184 | 185 | template 186 | void List::push_begin(T const& value) 187 | { 188 | ListElem *wrk = new ListElem; 189 | wrk->value = value; 190 | wrk->next = head; 191 | wrk->prev = nullptr; 192 | head = wrk; 193 | ++size; 194 | if(size == 1) 195 | tail = head; 196 | } 197 | 198 | template 199 | void List::push_end(T const& value) 200 | { 201 | ListElem *wrk = new ListElem; 202 | wrk->value = value; 203 | wrk->next = nullptr; 204 | if (is_empty()) 205 | { 206 | head = wrk; 207 | head->prev = nullptr; 208 | tail = head; 209 | ++size; 210 | return; 211 | } 212 | tail->next = wrk; 213 | wrk->prev = tail; 214 | tail = wrk; 215 | ++size; 216 | } 217 | 218 | template 219 | void List::push_after(T const& value, int n) 220 | { 221 | if ((n<0)||(n>=size)) 222 | throw OutOfRangeListExeption("push_after"); 223 | if((n>=0)&&(n *wrk = new ListElem; 226 | wrk->value = value; 227 | ListElem *it = head; 228 | for(int i = 0; inext; 230 | wrk->next = it->next; 231 | it->next = wrk; 232 | wrk->prev = it; 233 | it = wrk->next; 234 | it->prev = wrk; 235 | ++size; 236 | } 237 | else 238 | push_end(value); 239 | } 240 | 241 | template 242 | inline T List::delete_begin() 243 | { 244 | if(size == 0) 245 | throw EmptyListAccessExeption("delete_begin"); 246 | T value; 247 | ListElem *wrk = head; 248 | value = wrk->value; 249 | head = head->next; 250 | if (head) 251 | head->prev = nullptr; 252 | delete wrk; 253 | --size; 254 | return value; 255 | } 256 | 257 | template 258 | T List::delete_end() 259 | { 260 | if (size == 0) 261 | EmptyListAccessExeption("delete_end"); 262 | T value; 263 | ListElem *wrk = tail; 264 | value = tail->value; 265 | tail = tail->prev; 266 | tail->next = nullptr; 267 | delete wrk; 268 | --size; 269 | return value; 270 | } 271 | 272 | template 273 | void List::clear() 274 | { 275 | while(size>0) 276 | delete_begin(); 277 | } 278 | 279 | template 280 | T List::delete_index(int n) 281 | { 282 | if (is_empty()) 283 | throw EmptyListAccessExeption("delete_index"); 284 | if ((n<0)||(n>=size)) 285 | throw OutOfRangeListExeption("delete_index"); 286 | if((n>0)&&(n *wrk1 = head, *wrk2 = head; 290 | for(i = 0; inext; 293 | wrk2 = wrk2->next; 294 | } 295 | wrk1 = wrk1->next; 296 | wrk2->next = wrk1->next; 297 | wrk1->next->prev = wrk2; 298 | delete wrk1; 299 | --size; 300 | } 301 | else 302 | if(n == 0) 303 | delete_begin(); 304 | else 305 | delete_end(); 306 | } 307 | 308 | template 309 | int List::find(T const& value) 310 | { 311 | int i; 312 | ListElem *wrk = head; 313 | for(i = 0; i 320 | void List::show() 321 | { 322 | T wrk; 323 | for(int i = 0; i 332 | inline void List::swap(int n1, int n2) 333 | { 334 | T temp = get(n1); 335 | set(get(n2), n1); 336 | set(temp, n2); 337 | } 338 | 339 | template 340 | void List::sort() 341 | { 342 | ListElem *wrk1; 343 | T temp; 344 | int num; 345 | wrk1 = head; 346 | int i, j; 347 | for(i = 0; iget(j)) 354 | { 355 | temp = get(j); 356 | num = j; 357 | } 358 | } 359 | if (num!=i) 360 | swap(i, num); 361 | } 362 | } 363 | 364 | template 365 | List List::operator+(List &obj) 366 | { 367 | for(int i = 0; ipush_end(obj.get(i)); 369 | return *this; 370 | } 371 | 372 | template 373 | List List::operator =(List &obj) 374 | { 375 | clear(); 376 | List *wrk = new List(obj); 377 | this->head = wrk->head; 378 | this->tail = wrk->tail; 379 | this->size = wrk->size; 380 | return *this; 381 | } 382 | } 383 | 384 | #endif // LIST_HPP 385 | --------------------------------------------------------------------------------