Wild programming and design new thinking

xiaoxiao2021-03-06  81

Xu Jingzhou

UML software engineering organization

Foreword always remember, the purpose of writing code is to make it clear, do not use the language of the language, play smart, and important is to write your understanding code, understand the code you write, so you may do better. --- Herb Sutter In 1998, the international C standard was officially passed, and the standardization of C is the most important contribution to "powerful abstraction concept" to reduce software complexity, C provides two functions. Abstract method: object-oriented programming and generic programming. Object-oriented programming, you must be very familiar, here no longer. Remove generic programming, some people may not be familiar, but mentioned STL, you will have to hear. STL (Standard Template Library) is actually the implementation of generic programming, STL is developed by Alexander Stepanov (Father), David R Musser and Meng Lee, is incorporated into C standard procedures in 1994 Library. Although STL is relatively late to join the C standard library, it is the most revolutionary part of the C standard library, and is also the most important part of the C standard library. Because almost everything in the new C standard library is made by template, of course, STL will not exceed So, there is a need to first explain the concept of the template. Template concept With a template to make the program better code reuse. Remember, the template is reused the source code, not by inheriting and combining reuse object code, when the user uses templates, the parameters are replaced by the compiler. The template consists of two parts of the class template and function template, with the description of the data type as the parameter is called class template, and the description of the data type is called a function template. Template parameters can be composed of type parameters or non-type parameters. The type parameters can be specified by Class and TypeName keywords. The two senses are the same, which means that the back parameter name represents a potential built-in or user-defined type, non-type parameters A normal parameter declaration composition. Below is a simple usage of class template and function template: Template class queue // class template, where t1 is type parameters, size is non-type parameter {public: explicit queue (): size_ (size) { }; // Explicit constructor to avoid implicit conversion ... Template Void Assign (T2 First, T2 Last); // Inline Function Template Private: T * Temp_; int size _;} // class template Embedded Function Template COMPARE DETET (such as in the Queue Category Implement) Template Template Void Queue :: Assign (T2 First, T2 Last) {}; / / Template How to use int IA [4] = {0, 1, 2, 3}; Queue Qi; Qi.Assign (Ai, Ai 4); generic Programming generic programming and object-oriented programming, it does not require you to call a function through additional indirect layers, which allows you to write completely and reused algorithms, and the efficiency and algorithm designed for a particular data type the same. Generic programming representative works STL is an efficient, generic, interactive software component.

The so-called genericity refers to an integrated meaning on a variety of data types, which is similar to the template. STL is huge, and it can be expanded, which contains many computer basic algorithms and data structures, and the algorithm is fully separated from the data structure, where the algorithm is generic, not with any particular data structure or object type. STL is based on an iterators and container (Containers), which is a generic algorithms library, and the existence of containers makes these algorithms. STL contains various generic algorithms, generic pointers, generic containers, and Function Objects. STL is not only a collection of useful components, which is a formal and organized architecture that describes the abstract demand conditions of software components. Iterators is the core of STL, which is a generic pointer, an object that points to other objects (Objects), and iterator can traverse the interval formed by the object. The iterator allows us to separate the container (containers) to the algorithms on which most of the algorithms do not directly operate directly on the container, but is operated in the interval formed by the iterator. Iterator is generally divided into five: Input Iterator, Output Iterator, Forward Iterator, Bidirections Iterator and Random Access Iterator. Input Iterator is like only read data from the input interval, which belongs to one-way movement, such as ISTREAM_ITERATOR in STL. Output Iterator is just the opposite, only written to the output interval, with only written, belonging to the OSTREAM_ITERATOR in STL. The Forward Iterator also belongs to one-way, but the difference is that it has data read, write. Bidirections Iterator, such as name, supporting two-way movement, not only can accumulate ( ) to get the next element, but can be decremented (-) to take the previous elements, support read, write. The Random Access Iterator function is the strongest. In addition to the above iterator features, random elements access (P = N), subscript (P [n]), subtractive (P1-P2) and front-order relationship (P1 < P2), etc. Input Iterator and Output Iterator are the equivalents of two iterators, and Forward Iterator is a REFINEMENT. The Bidirections iterator is also strengthened, and the last Random Access Iterator is the Bidirections Iterator iterator. strengthen.

The following simple example shows Input Iterator, Forward Iterator, Bidirections Iterator and Radom Access Iterator iterator functions (like wherein input_iterator_tag string tag with unique identifying various iterator): 1, InputIteratortemplate void advance (InputITERATOR & I, DISTANCE N, INPUT_ITERATOR_TAG) {for (; n> 0; - N, i) {} // inputiterator has sex} 2, ForwardItemTemplate Void Advance (ForwardIterator & i , Distance n, forward_iterator_tag) {advance (i, n, input_iterator_tag ());} 3, BidirectionalIteratortemplate void advance (BidirectionalIterator & i, Distance n, bidirectional_iterator_tag) {if (n> = 0) // With ,-sex for (; n> 0; - N, i) {} elsefor (; n> 0; n, - i) {}} 4, RandomaccessItemTemplate Void Advance (RandomaccessITerator & I, DISTANCE N, RANDOM_ACCESS_ITERATOR_TAG) {i = n; // has , -, = equality} function object (function object), is also known as the functor, is a kind The object that can call the syntax by the general function to call the syntax, a function pointer is a function object, all of which have an Operator () operator overloaded member function is also a function object. Function objects are generally divided into three forms of unary function (unary function), binary function, which can be f (), f (x) and f (x, y) The form is called, and all other function objects defined by STL are enhanced in these three concepts.

Simply exemplified as follows: 1. Non-collapse (generator) Struct counter {typef Int result_type; counter (Result_type init = 0): n (init) {} result_type operator () {Return n ;} result_type n } 2, Unary Function Form Template struct evenuN // Function object Even, find the first even {BOOL OPERATOR () (Number X) const {return (x & 1) == 0;} } // Use the algorithm FIND_IF to find an element that satisfies the function object EVEN in the interval A to A N, INT A [] = {1, 0, 3, 4}; const Int n = sizeof (a) / sizeof (int); Find_if (a, a n, even ()); 3, binary function form Struct ltstr {bool operator () (const char * s1, const char * s2) const {return strcmp (S1 < S2) <0;}}; // Using function objects LTSTR, output SET container CONST INT N = 3Const char * a [n] = {"xjz", "xzh", "gh"} Const char * b [n] = {"jzx", "zhx", "abc"}; set A (A, A N); set b ( B, B N); set_union (a.begin (), a.end (), b.begin (), B.End (), ostream_iterator (cout, "), ltstr ()) Container is an object that can contain and manage other objects and provide an iterators to address elements contained there. According to the different types of iterators, the container is also divided into a few, with the general Container for the Iterator iterator, with the Forward Iterator as an iterator, the Reversible Container, which is the Random Access Iterator, based on the Random Access Iterator as iterator. The Random Access Container of the device. STL defines two sizes of variable containers: Sequence Container and Associative Container Sequence containers include Vector, List, and Deque, associated containers include SET, MAP, MULTISET, and MULTIMAP.

The following example briefly describes the use of partial containers: 1, Vector use // to split a in element 5, separately sorted, so that the elements behind the sort 5 have been more than 5 (the rear interval is not sorted), then output Int main () {int a [] = {7, 2, 6, 4, 5, 8, 9, 3, 1}; const Int n = sizeof (a) / sizeof (int); vector v) A, A N); Partial_Sort (V, V 5, V N); COPY (v, v n, ostream_iterator (cout, ")); cout << Endl;} Output may be: 1 2 3 4 5 8 9 7 62, List uses // Generate an empty list, sort the element, then output int main () {list L1; l1.push_back (0); l1.push_front (1); L1.INSERT ( L1.Begin, 3); l1.sort (); copy (l1.begin (), l1.end (), ostream_iterator (cout, "));} Output: 0 1 33, Deque use int main () {Deque q; q.push_back (3); q.push_front (1); Q.insert (q.begin () 1, 2); copy (q.begin ), Q.End (), ostream_iterator (cout, "));} Output: 1 2 34, MAP use int main () {map m; m.insert (Make_Pair (" A ", 11); Pair :: item, bool> p = m.insert (make_pair (" c ", 5)); if (p.second) cout << p.first-> second << Endl;} Output: 55, MultiSet Using Int Main () {const INT N = 5; INT A [N] = {4, 1, 1, 3, 5}; MultiSet A (A, A N); copy (A.Begin (), a.end (), ostream_iterator (cout, "));} Output: 1 1 3 4 5 Design new thinking will design mode (Design Patterns), generic Generic Pro Gramming) and object-oriented programming organic combination, form new thinking. Among them, the design model is a refined outstanding design method, and it is a reasonable and reusable solution for many situations; generic programming is a model of paradigm, focusing on type abstraction , Form a fine set in terms of functional requirements, and utilize these requirements to implement algorithms, the same algorithm can be used in a wide range of types, so-called generics, it is possible to operate in a variety of data types; The polymorphism and template (Templates) such as object program are combined to obtain a high level of generic components. The generic components advance the design module in advance, allowing users to specify types and behaviors to form reasonable design, mainly feature flexible, universal, and easy to use.

Policies and Policy classes are an important class design technology that is used to define a class or class template interface that consists of the following or all of the following: internal type definitions, member functions, and member variables. The POLICY-based class consists of many small classes (called policies), each such small classes are only responsible for some aspects of behavior or structures. The Policies mechanism consists of templates and multiple inherits, which can be mixed with each other, thereby forming a diversity of design, but can customize behavior through the PLICY class, but also can be customized. The following is a simple example of the use of generalized thinking and object-oriented thinking in some design modes. Singletons Design Mode Ultrafining Singleton mode is a guaranteed an object (Class) only one entity and provides a global access point. Singleton is an improved global variable that is only available in the program, which focuses on generating and managing a separate object, and does not allow another such object. Let us first look at the basic technique of general C implementation, the following is the implementation source: // singleleton.h file Class Singleton {public: static singleleton & instance () {if (! Pinstance _) {if (destroyed _) {// reference Whether it has failed overdeadreference ();} else {create (); // Create an instance}} Return * Pinstance_;} private: Singleton (); // Prohibited Singleton (Const Singleton &); // Disable copy configured Singleton & operator = (const Singleton &); // prohibiting assignment static void Create () // example pass plus reference created {static Singleton theInstance; pInstance_ = & theInstance;} static void OnDeadReference () {throw std :: runtime_error ( " Examples were accidentally destroyed ");} Virtual ~ singleton () {pinstance- = 0; destroyed_ = true;} static singleton * pinstance_; static bool destroyed _;} // singleleton.cpp In static member variables Initializing Singleton * Singleton: : Pinstance_ = 0; Bool Singleton :: DESTROYED_ = false; As shown above, only one public member instance () in the Singleton mode implementation is used to create a single instance when used, and the static variable will have been Set well, do not create an instance again. The default constructor, copy constructor, and assignment operator are also placed in Private, and the location is not allowed to use them. In addition, in order to avoid instantiation after instance unexpected destruction, the static Boolean variable destroy_ is added to determine whether it is wrong to achieve stability. It can be seen from the above general implementation that the Singleton mode implementation is mainly in creating aspects and LifeTime, which can create Singleton through various methods. Creation inevitably creates and destroys objects, inevitably open these two corresponding functions, will be created as an independent policy to separate, so you can create polymorphism objects, so the generalization Singleton does not have Creator objects, it Placed in the CreationPolicy Template.

The life period refers to the C rules, and then created first destroyed, and the procedure life period destroys the Singleton object at a time. Here is realized a simple generalization Singleton Pattern (without regard to thread factor) template calss CreationPolicy = CreateUsingNew, template class LifetimePolicy = DefaultLifetime,> classs SingletonHolder {public: static T & Instance ( ) {if (pInstance _) {if (destroyed_) {LifetimePolicy :: OnDeadReference ();! destroyed_ = false;} pInstance_ = CreationPolicy :: Create (); LifetimePolicy :: SchedultCall (& DestorySingleton) ;} return * pInstance _;} private: (! destroyed _) static void DestroySinleton () {assert; CreationPlicy :: Destroy (pInstance _); pInstance_ = 0; destroyed_ = true;} SingletonHolder (); SingletonHolder (const SingletonHolder & ); SingletonHolder & operator = (const SingletonHolder &); Static T * pInstance_; Static bool destroyed _;}; Instance () is only open SingletonHolder a public function, which create a layer of shell CreationPolicy, LifetimePolicy in. Among them, the template parameter type T, receive the class name, and both of the class of Singleton needs. The class template within the template parameter default parameter createusingNew refers to the object by the New operator and the default constructor, and the defaultlifetime is used to manage the life period through the C rules. There are two member functions in LifetimePolicy , and the ScheduleDestrution () function accepts a function pointer, pointing to the actual execution function of the destructure operation, as described above DestorySingleton destructor; ONDEADREFERENCE () function is the same as the same name in the general C above, is Responsible for discovering the failure instance to throw an abnormality. CreationPlicy The Create () and Destroy () two functions are used to create and destroy specific objects.

转载请注明原文地址:https://www.9cbs.com/read-93017.html

New Post(0)