여러 순차 작업의 결과를 한 번에 보여준다.
버퍼 클래스는 변경이 가능한 상태인 버퍼를 캡슐화한다. 버퍼는 점차적으로 수정되지만, 밖에서는 한 번에 바뀌는 것처럼 보이게 하고 싶다. 이를 위해서 버퍼 클래스는 현재 버퍼와 다음 버퍼, 이렇게 두 개의 버퍼를 갖는다.
정보를 읽을 때는 항상 현재 버퍼에 접근한다. 정보를 쓸 때는 항상 다음 버퍼에 접근한다. 변경이 끝나면 다음 버퍼와 현재 버퍼를 교체해 다음 버퍼가 보여지게 한다. 현재 버퍼는 새로운 다음 버퍼가 되어 재사용된다.
#include <iostream>
using namespace std;
class Framebuffer {
public:
Framebuffer() { Clear(); }
void Clear() {
for (int i = 0; i < WIDTH * HEIGHT; ++i) {
pixels_[i] = '0';
}
}
void Draw(int x, int y)
{
pixels_[(WIDTH * y) + x] = '1';
}
const char* GetPixels() { return pixels_; }
private:
static const int WIDTH = 160;
static const int HEIGHT = 120;
char pixels_[WIDTH * HEIGHT];
};
class Scene{
public:
Scene() : current_(&buffers_[0]), next_(&buffers_[1]) {}
void Draw() {
next_->Clear();
next_->Draw(1, 1);
next_->Draw(4, 1);
next_->Draw(1, 3);
next_->Draw(2, 4);
next_->Draw(3, 4);
next_->Draw(4, 3);
Swap();
}
private:
void Swap() {
Framebuffer* temp = current_;
current_ = next_;
next_ = temp;
}
Framebuffer buffers_[2];
Framebuffer* current_;
Framebuffer* next_;
};
int main()
{
Scene scene;
scene.Draw();
}