Design Patterns Difficult to describe abstractly Elements: Pattern Name Problem to Solve Solution Consequences: Results and Trade-Offs Higher level abstraction than classes
Example: Singleton Intent: Define a class pattern that is guaranteed to have only one instance, and provide a global point of access to it. Uses A good global variable/class Simulator has one radar, one physical display, etc.
Singleton Implementation Class Singleton { public: static Singleton* Instance(); protected: Singleton(); private: static Singleton* _instance; }; Singleton* Singleton::Instance = 0; Singleton* Singleton::Instance() { if (_instance == 0) { _instance = new Singleton; } return _instance;
Example: Abstract Factory Provide and interface for creating families of related or dependent objects without specifying their concrete class. A system can be created that is independent of how its elements(products) are created, composed, and represented Participants: Abstract Factory (WidgetFactory): interface to the client Concrete Factory(MotifWidgetFactory, MFCWidgetFactory): implements the abstract interface Abstract Product(Window, Scrollbar): what the client sees Concrete Product(MotifWindow, MotifScrollBar): defines the actual object Client: who uses the products via the abstract interfaces
Iterator Goal: Provide a way to sequentially access the elements of an aggregate object without exposing its underlying representation. Using an iterator, it would be possible to replace an array with a linked list or binary tree This construct is heavily used in STL
Iterator Implementation Template <class Item> class Iterator { public: virtual void First() = 0; virtual void Next()= 0; virtual bool IsDone() const = 0; virtual Item CurrentItem const = 0; protected: Iterator(); };
List Iterator Template <class Item> class ListIterator : public Iterator<Item> { public: ListIterator(const List<Item>* aList); virtual void First(); … private: const List<Item>* _list; long _current; };
STL Standard Template Libaray: Part of C++ Objects vector list map & multimap set & multiset deque (double ended queues) stack, queue, priority_queue
STL cont’d All objects have iterators Generic Algorithms can be done on these objects for_each, find, count, equal, search, sort, fill, merge, etc.