Design Pattern --- FlyWeight
struct Context { int x, y; }; class FlyWeight { // data. const string m_str; public: FlyWeight(const string &str) : m_str(str) {} public: // Interface. void draw(Context &c) { cout <<c.x <<" : " <<c.y <<" => " <<m_str <<endl; } }; int main(int argc, char *argv[]) { Context c1 = {4, 8}, c2 = {0, -4}, c3 = {-1, 2}, c4 = {9, 2}; FlyWeight f1("abcdefg"), f2("12345678"); // 这里只有两个字符串对象, 这是稳定的内容. 但是可以和很多个表示易变信息的 Context 对象组合在一起, // 而不必每个 Context 都有相同的字符串. 因此节省了内存. f1.draw(c1); f1.draw(c2); f1.draw(c3); f2.draw(c1); f2.draw(c2); f2.draw(c3); f2.draw(c4); return 0; }
FlyWeight 的优势在于有非常多的对象都拥有共同的数据成员. 这种情况下我们就可以通过抽象, 将易变部分提取出来. 这就是 FlyWeight 的意图.
设计模式的核心思想就是, 分离和封装变化.