본문 바로가기
C++/0x01-design pattern

composite pattern

by SpeeDr00t 2016. 7. 14.
반응형

composite pattern

1.소스

#include <iostream>
#include 
using namespace std;

// 2. Create an "interface" (lowest common denominator)
class Component
{

public:
    virtual void traverse() = 0;
};


class Leaf: public Component
{

// 1. Scalar class   3. "isa" relationship
int value;

public:
    Leaf(int val)
    {
        value = val;
    }
    void traverse()
    {
        cout << value << ' ';
    }
};


class Composite: public Component
{

// 1. Vector class   3. "isa" relationship
vector < Component * > children; // 4. "container" coupled to the interface

public:
    // 4. "container" class coupled to the interface
    void add(Component *ele)
    {
        children.push_back(ele);
    }
    void traverse()
    {
        for (int i = 0; i < children.size(); i++)
        // 5. Use polymorphism to delegate to children
          children[i]->traverse();
    }
};

int main()
{
    Composite containers[4];

    for (int i = 0; i < 4; i++) 
	{
        for (int j = 0; j < 3; j++) {
            containers[i].add(new Leaf(i *3+j));
		}
    }

    for (i = 1; i < 4; i++) {
        containers[0].add(&(containers[i]));
	}

    for (i = 0; i < 4; i++)
    {
        containers[i].traverse();
        cout << endl;
    }
}

2.결과

g++ -o composite composite.cpp
hacker@HACKER:~/cpp$ ./composite
0 1 2 3 4 5 6 7 8 9 10 11
3 4 5
6 7 8
9 10 11
반응형

'C++ > 0x01-design pattern' 카테고리의 다른 글

facade pattern  (0) 2016.07.14
decorator pattern.  (0) 2016.07.14
Observer pattern  (0) 2016.07.14
design pattern ][ Abstract Factory pattern  (0) 2016.07.14
state 패턴  (0) 2016.07.14