Zane Shelley | 200c345 | 2019-09-26 11:46:30 -0500 | [diff] [blame^] | 1 | #include <util/hei_flyweight.hpp> |
| 2 | |
| 3 | #include "gtest/gtest.h" |
| 4 | |
| 5 | using namespace libhei; |
| 6 | |
| 7 | class Foo |
| 8 | { |
| 9 | public: |
| 10 | Foo() = default; |
| 11 | explicit Foo( int i ) : iv_i(i) {} |
| 12 | int get() const { return iv_i; } |
| 13 | bool operator==( const Foo & i_r ) const { return iv_i == i_r.iv_i; } |
| 14 | bool operator<( const Foo & i_r ) const { return iv_i < i_r.iv_i; } |
| 15 | private: |
| 16 | int iv_i = 0; |
| 17 | }; |
| 18 | |
| 19 | Flyweight<Foo> factory {}; |
| 20 | |
| 21 | Foo & addFoo( int i ) |
| 22 | { |
| 23 | Foo f { i }; |
| 24 | return factory.get( f ); |
| 25 | } |
| 26 | |
| 27 | TEST( FlyweightTest, TestSet1 ) |
| 28 | { |
| 29 | // Add some unique entries in a random order and keep track of where those |
| 30 | // enties exist in memory. |
| 31 | Foo * a[5]; |
| 32 | a[1] = &(addFoo(1)); |
| 33 | a[2] = &(addFoo(2)); |
| 34 | a[0] = &(addFoo(0)); |
| 35 | a[4] = &(addFoo(4)); |
| 36 | a[3] = &(addFoo(3)); |
| 37 | |
| 38 | // Now add more entries and verify the 'new' entries match the same |
| 39 | // addresses as the previously added entries. |
| 40 | for ( int i = 4; i >= 0; i-- ) |
| 41 | { |
| 42 | ASSERT_EQ( a[i], &(addFoo(i)) ); |
| 43 | } |
| 44 | |
| 45 | // At this point, we have proven that duplicate entries will return |
| 46 | // references to the original unique entries. There is probably more we can |
| 47 | // do here, but this is enough to prove the Flyweight class follows the |
| 48 | // flyweight design pattern. |
| 49 | } |