The design patterns in the software field provide developers with an effective way to use expert design experience. Objects are used in the design model.Programming LanguageImportant features: encapsulation, inheritance, polymorphism, true understanding of the essence of the design model is a long process that requires a lot of practical experience. I recently read a book on design patterns. I wrote a small example in C ++ for each pattern to help me better understand it. Refer to "big talk Design Patterns" and "design patterns: the basis for reusable object-oriented software" (DP. This article describes how to implement the adapter mode.
Definition on DP: the adapter mode converts an interface of a class to another interface that the customer wants, so that classes that cannot work together due to interface incompatibility can work together.. It includes class adapters and object adapters. This article is about object adapters. For example, the adapter mode is used in STL. STL implements a data structure called deque, which supports insertion and deletion of the first and second segments. When STL implements stacks and queues, they are directly implemented using dual-end queues instead of being defined from the beginning. The dual-end queue plays the role of the adapter. The queue uses its backend insertion and the frontend deletion. The stack uses its backend inserts and deletes the backend. Assume that the stack and the queue are both ordered containers. There are two operations: press-in and pop-up.The corresponding UML diagram is given below, which is similar to the diagram on DP.
Based on the above UML diagram, it is easy to provide implementation.
// Double-end queue class deque {public: void push_back (int x) {cout <"deque push_back" <Endl;} void push_front (int x) {cout <"deque push_front" <Endl;} void pop_back () {cout <"deque pop_back" <Endl;} void pop_front () {cout <"deque pop_front" <Endl ;}; // sequence container class sequence {public: Virtual void push (int x) = 0; virtual void POP () = 0 ;}; // Stack class Stack: Public sequence {public: void push (int x) {deque. push_back (x);} void POP () {deque. pop_back ();} PRIVATE: deque; // double-end queue}; // queue class queue: Public sequence {public: void push (int x) {deque. push_back (x);} void POP () {deque. pop_front ();} PRIVATE: deque; // double-end queue };
The usage is as follows:
Int main () {sequence * S1 = new stack (); sequence * S2 = new Queue (); S1-> push (1); S1-> POP (); s2-> push (1); S2-> POP (); Delete S1; Delete S2; return 0 ;}
I am entitled to the copyright of my blog Article , indicate the source for reprinting. Http://blog.csdn.net/wuzhekai1985