Design pattern iterator mode (Iterator) excerpt

Source: Internet
Author: User

23 Kinds of GOF design patterns are generally divided into three categories: the creation mode, the structure pattern, the behavior pattern.

The Create pattern abstracts the instantiation process, which helps a system to be independent of the objects that create, group, and represent it. A class-creation pattern uses inheritance to change the class that is instantiated, and an object-creation pattern entrusts the instantiation to another object. The creation pattern has two recurring themes. First, they encapsulate the information about which detailed classes the system uses. Second, they hide how instances of these classes are created and put together. What the whole system knows about these objects is the interfaces defined by the abstract classes. Thus, creating a pattern gives very great flexibility in what is created, who creates it, how it is created, and when it is created. They agree to configure a system with "product" objects that differ very much in structure and function. The configuration can be static (that is, specified at compile time), or it can be dynamic (at execution time).

Structured patterns involve how classes and objects are combined to get a larger structure. The structure class pattern adopts the inheritance mechanism to combine interfaces or implementations. A structured object pattern is not a combination of interfaces and implementations, but rather a description of some of the ways in which some objects are combined to achieve new functionality. Because of the ability to change the composition of objects at execution time, object composition is more flexible, and this mechanism is not possible with static class combinations.

Behavioral patterns involve the allocation of duties between algorithms and objects. The behavior pattern not only describes the patterns of objects or classes, but also describes the communication patterns between them. These patterns depict complex control flows that are difficult to track at execution time. They shift the user's attention from the control flow to the contact between objects. The behavior class pattern uses the inheritance mechanism to dispatch behavior between classes. The Behavior object pattern uses object compositing instead of inheritance. Some behavioral object pattern descriptions describe how a set of peers can work together to complete a task in which either object cannot be completed alone.

The creation pattern consists of: 1, FactoryMethod (factory method mode), 2, abstract Factory (Abstraction Factory mode), 3, Singleton (singleton mode), 4, builder (builder mode, generator mode), 5, Prototype (prototype mode).

The structure mode includes : 6, Bridge (bridging mode), 7, Adapter (adapter mode), 8, Decorator (decorative mode), 9, Composite (combination mode), 10, Flyweight (enjoy meta-mode); 11, Facade (appearance mode), 12, Proxy (agent mode).

behavioral patterns include : 13, Templatemethod (template method mode), 14, strategy (strategy mode), 15, State (status mode), 16, OBSERVER (Observer mode), 17, Memento (Memo mode 18, Mediator (intermediary mode), 19, command (order mode), 20, Visitor (Interview mode), 21, Chain of Responsibility (responsibility chain mode), 22, Iterator (iterator mode), 23, Interpreter (interpreter mode).

Factory Method: Defines an interface for creating objects, so that subclasses decide which class to instantiate. The Factory method defers the instantiation of a class to its subclasses.

Abstract Factory: Provides an interface to create a series of related or interdependent objects without specifying their detailed classes.

Singleton: Ensure that a class has only one instance and provides a global access point to it.

Builder: Separates the construction of a complex object from its representation so that the same build process can create different representations.

Prototype: Specifies the kind of object created with the prototype instance, and creates a new object by copying the prototype.

Bridge: Separates the abstract part from its implementation, so that both can change independently.

Adapter: Transforms the interface of a class into another interface that the customer wants. The adapter mode makes it possible for those classes that would otherwise not be able to work together because of incompatible interfaces.

Decorator: Dynamically add some additional responsibilities to an object. In terms of extended functionality, the decorator mode is more flexible than the way the subclass is generated.

Composite: Combines objects into a tree structure to represent a "partial-overall" hierarchy. Composite enables customers to have consistent use of individual objects and composite objects.

Flyweight: Use sharing technology to effectively support a large number of fine-grained objects.

facade: Provides a consistent interface for a set of interfaces in a subsystem, and the facade schema defines a high-level interface that makes this subsystem easier to use.

Proxy: Provides an agent for other objects to control access to this object.

Template Method: Defines the skeleton of an algorithm in an operation, and delays some steps into subclasses. The Template method allows subclasses to redefine some specific steps of the algorithm without altering the structure of an algorithm.

Strategy: Define a series of algorithms, encapsulate them one by one, and make them interchangeable with each other. This mode allows the algorithm to be changed independently of the customer using it.

State: Agrees that an object changes its behavior when its internal states change. The object appears to have changed the class it belongs to.

Observer: Defines a one-to-many dependency between objects so that when the state of an object changes, all objects that depend on it are notified and refreshed on their own initiative.

Memento: captures the internal state of an object without compromising encapsulation, and saves the state outside that object. The object can then be restored to the saved state.

Mediator: Encapsulates a series of object interactions with a mediation object. Intermediaries allow objects to be loosely coupled without having to explicitly cross-reference each other, and can independently change the interaction between them.

Command: Encapsulates a request as an object, so that you can use different requests to account for the customer, queue up requests or log requests, and support actions that can be canceled.

Visitor: Represents an operation that acts on elements in an object's structure. It enables you to define new actions that act on these elements without changing the class of each element.

Chain of Responsibility: a coupling between the sender and receiver of the cancellation request, allowing multiple objects to have the opportunity to process the request. Link the objects together and pass the request along the chain until an object handles it.

Iterator: Provides a way to access individual elements of an aggregation object in a sequential manner without exposing the object's internal representation.

interpreter: Given a language, defines a representation of its grammar and defines an interpreter that uses that representation to interpret sentences in the language.

Iterator: (1), intent: Provides a way to access the individual elements of an aggregation object without exposing the internal representation of the object. Provides a unified interface for traversing different aggregation structures, such as start, next, end, current, and so on.

(2), applicability: A, access to the content of an aggregated object without exposing its internal representation. B, support for multiple traversal of the aggregation object. C, provide a unified interface for traversing different aggregation structures (that is, multi-state iterations are supported).

(3) Advantages and disadvantages: A, it supports traversing an aggregation in different ways: complex aggregations can be traversed in many ways. For example, code generation and semantic checking will traverse the parsing tree. Code generation can traverse the parsing tree either in the middle order or in the pre-order. Iterators make it very easy to change the traversal algorithm: replace the original instance with only one instance of a different iterator. You can also customize the subclass of the iterator to support the new traversal. B, iterators simplify the interface of aggregation: with an iterator traversal interface, the aggregation itself no longer requires a similar traversal interface. This simplifies the interface of the aggregation. C, there can be multiple traversal on the same aggregation: each iterator maintains its own traversal state. So you can do multiple traversal at the same time.

(4), correlation mode: A, Composite: iterators are often applied to such recursive structures as composite. B, Factory method: A polymorphic iterator by Factory method to instantiate the appropriate iterator subclass. C, Memento: Often used in conjunction with the iterator pattern. Iterators can use a memento to capture the state of an iteration. The iterator stores the memento inside it.

Demo Sample code:

Aggregate.h:

#ifndef _aggregate_h_#define _aggregate_h_class iterator;typedef int object;class interator;class Aggregate{public: Virtual ~aggregate (); virtual iterator* createiterator () = 0;virtual Object GetItem (int idx) = 0;virtual int getsize () = 0; Protected:aggregate ();p rivate:};class concreteaggregate:public aggregate{public:enum {SIZE = 3}; Concreteaggregate (); ~concreteaggregate (); iterator* createiterator (); Object GetItem (int idx); int getsize (); Protected:private:Object _objs[size];}; #endif//~_aggregate_h_

Aggregate.cpp:

#include "Aggregate.h" #include "Iterator.h" #include <iostream>using namespace std; Aggregate::aggregate () {}aggregate::~aggregate () {}concreteaggregate::concreteaggregate ()} {for (int i = 0; i < SIZE; I + +) _objs[i] = i;} Concreteaggregate::~concreteaggregate () {}iterator* concreteaggregate::createiterator () {return new Concreteiterator (this);} Object concreteaggregate::getitem (int idx) {if (idx < this->getsize ()) return _objs[idx];elsereturn-1;} int Concreteaggregate::getsize () {return SIZE;}

Iterator.h:

#ifndef _iterator_h_#define _iterator_h_class aggregate;typedef int object;class iterator{public:virtual ~Iterator (); virtual void first () = 0;virtual void Next () = 0;virtual bool IsDone () = 0;virtual Object CurrentItem () = 0;protected:iter Ator ();p rivate:};class concreteiterator:public iterator{public:concreteiterator (aggregate* ag, int idx = 0); ~ Concreteiterator (); void first (); void Next (); bool IsDone (); Object CurrentItem ();p rotected:private:aggregate* _ag;int _idx;}; #endif//~_iterator_h_

Iterator.cpp:

#include "Iterator.h" #include "Aggregate.h" #include <iostream>using namespace Std;iterator::iterator () {} Iterator::~iterator () {}concreteiterator::concreteiterator (aggregate* AG, int idx) {This->_ag = Ag;this->_idx = IDX;} Concreteiterator::~concreteiterator () {}object Concreteiterator::currentitem () {return _ag->getitem (_IDX);} void Concreteiterator::first () {_idx = 0;} void Concreteiterator::next () {if (_idx < _ag->getsize ()) _idx + +;} BOOL Concreteiterator::isdone () {return (_idx = = _ag->getsize ());}

Main.cpp:

#include "Iterator.h" #include "Aggregate.h" #include <iostream>using namespace Std;int main () {aggregate* AG = new Concreteaggregate (); iterator* it = new Concreteiterator (AG); for (;!) ( It->isdone ()); It->next ()) Cout<<it->currentitem () <<endl;/*result012*/return 0;}

Iterator pattern structure diagram:


References:

1, "Big talk design mode C + +"

2, "design pattern refinement----GoF23 design mode Analysis"

3. Design mode----The basis of reusable object-oriented software

Design pattern iterator mode (Iterator) excerpt

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.