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 | |
Zane Shelley | 200c345 | 2019-09-26 11:46:30 -0500 | [diff] [blame] | 19 | Foo & addFoo( int i ) |
| 20 | { |
Zane Shelley | fc7ab19 | 2019-09-27 15:45:16 -0500 | [diff] [blame] | 21 | return Flyweight<Foo>::getSingleton().get( Foo { i } ); |
Zane Shelley | 200c345 | 2019-09-26 11:46:30 -0500 | [diff] [blame] | 22 | } |
| 23 | |
| 24 | TEST( FlyweightTest, TestSet1 ) |
| 25 | { |
| 26 | // Add some unique entries in a random order and keep track of where those |
| 27 | // enties exist in memory. |
| 28 | Foo * a[5]; |
| 29 | a[1] = &(addFoo(1)); |
| 30 | a[2] = &(addFoo(2)); |
| 31 | a[0] = &(addFoo(0)); |
| 32 | a[4] = &(addFoo(4)); |
| 33 | a[3] = &(addFoo(3)); |
| 34 | |
| 35 | // Now add more entries and verify the 'new' entries match the same |
| 36 | // addresses as the previously added entries. |
| 37 | for ( int i = 4; i >= 0; i-- ) |
| 38 | { |
| 39 | ASSERT_EQ( a[i], &(addFoo(i)) ); |
| 40 | } |
| 41 | |
| 42 | // At this point, we have proven that duplicate entries will return |
| 43 | // references to the original unique entries. There is probably more we can |
| 44 | // do here, but this is enough to prove the Flyweight class follows the |
| 45 | // flyweight design pattern. |
| 46 | } |