Issue#550: double buffer pattern (#1024)

* Basic implementation

* implement double buffer

* add unit test

* add unit test

* Add Readme

* Change local value declaration to var

* Remove unused fields
This commit is contained in:
Azureyjt 2019-10-20 23:55:36 +08:00 committed by Ilkka Seppälä
parent 82f9a6c232
commit 2217fbc5ff
11 changed files with 623 additions and 0 deletions

29
double-buffer/README.md Normal file
View File

@ -0,0 +1,29 @@
---
layout: pattern
title: Double Buffer
folder: double-buffer
permalink: /patterns/double-buffer/
categories: Other
tags:
- Java
- Difficulty-Beginner
---
## Intent
Double buffering is a term used to describe a device that has two buffers. The usage of multiple buffers increases the overall throughput of a device and helps prevents bottlenecks. This example shows using double buffer pattern on graphics. It is used to show one image or frame while a separate frame is being buffered to be shown next. This method makes animations and games look more realistic than the same done in a single buffer mode.
## Applicability
This pattern is one of those ones where youll know when you need it. If you have a system that lacks double buffering, it will probably look visibly wrong (tearing, etc.) or will behave incorrectly. But saying, “youll know when you need it” doesnt give you much to go on. More specifically, this pattern is appropriate when all of these are true:
- We have some state that is being modified incrementally.
- That same state may be accessed in the middle of modification.
- We want to prevent the code thats accessing the state from seeing the work in progress.
- We want to be able to read the state and we dont want to have to wait while its being written.
## Credits
* [Game Programming Patterns - Double Buffer]([http://gameprogrammingpatterns.com/double-buffer.html](http://gameprogrammingpatterns.com/double-buffer.html))

49
double-buffer/pom.xml Normal file
View File

@ -0,0 +1,49 @@
<?xml version="1.0" encoding="UTF-8"?>
<!--
The MIT License
Copyright © 2014-2019 Ilkka Seppälä
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.
-->
<project xmlns="http://maven.apache.org/POM/4.0.0"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<parent>
<artifactId>java-design-patterns</artifactId>
<groupId>com.iluwatar</groupId>
<version>1.22.0-SNAPSHOT</version>
</parent>
<modelVersion>4.0.0</modelVersion>
<artifactId>double-buffer</artifactId>
<dependencies>
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
</dependency>
<dependency>
<groupId>org.apache.commons</groupId>
<artifactId>commons-lang3</artifactId>
</dependency>
</dependencies>
</project>

View File

@ -0,0 +1,85 @@
/**
* The MIT License
* Copyright (c) 2014-2016 Ilkka Seppälä
* <p>
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
* <p>
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
* <p>
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*/
package com.iluwatar.doublebuffer;
import org.apache.commons.lang3.tuple.MutablePair;
import org.apache.commons.lang3.tuple.Pair;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.util.ArrayList;
import java.util.List;
/**
* Double buffering is a term used to describe a device that has two buffers.
* The usage of multiple buffers increases the overall throughput of a device
* and helps prevents bottlenecks. This example shows using double buffer pattern
* on graphics. It is used to show one image or frame while a separate frame
* is being buffered to be shown next. This method makes animations and games
* look more realistic than the same done in a single buffer mode.
*/
public class App {
private static final Logger LOGGER = LoggerFactory.getLogger(App.class);
/**
* Program main entry point.
* @param args runtime arguments
*/
public static void main(String[] args) {
var scene = new Scene();
List<Pair<Integer, Integer>> drawPixels = new ArrayList<>();
Pair<Integer, Integer> pixel1 = new MutablePair<>(1, 1);
Pair<Integer, Integer> pixel2 = new MutablePair<>(5, 6);
Pair<Integer, Integer> pixel3 = new MutablePair<>(3, 2);
drawPixels.add(pixel1);
drawPixels.add(pixel2);
drawPixels.add(pixel3);
scene.draw(drawPixels);
var buffer1 = scene.getBuffer();
printBlackPixelCoordinate(buffer1);
drawPixels.clear();
Pair<Integer, Integer> pixel4 = new MutablePair<>(3, 7);
Pair<Integer, Integer> pixel5 = new MutablePair<>(6, 1);
drawPixels.add(pixel4);
drawPixels.add(pixel5);
scene.draw(drawPixels);
Buffer buffer2 = scene.getBuffer();
printBlackPixelCoordinate(buffer2);
}
private static void printBlackPixelCoordinate(Buffer buffer) {
var log = "Black Pixels: ";
Pixel[] pixels = buffer.getPixels();
for (var i = 0; i < pixels.length; ++i) {
if (pixels[i] == Pixel.BLACK) {
var y = i / FrameBuffer.WIDTH;
var x = i % FrameBuffer.WIDTH;
log += " (" + x + ", " + y + ")";
}
}
LOGGER.info(log);
}
}

View File

@ -0,0 +1,56 @@
/**
* The MIT License
* Copyright (c) 2014-2016 Ilkka Seppälä
* <p>
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
* <p>
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
* <p>
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*/
package com.iluwatar.doublebuffer;
/**
* Buffer interface.
*/
public interface Buffer {
/**
* Clear the pixel in (x, y).
* @param x X coordinate
* @param y Y coordinate
*/
void clear(int x, int y);
/**
* Draw the pixel in (x, y).
* @param x X coordinate
* @param y Y coordinate
*/
void draw(int x, int y);
/**
* Clear all the pixels.
*/
void clearAll();
/**
* Get all the pixels.
* @return pixel list
*/
Pixel[] getPixels();
}

View File

@ -0,0 +1,68 @@
/**
* The MIT License
* Copyright (c) 2014-2016 Ilkka Seppälä
* <p>
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
* <p>
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
* <p>
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*/
package com.iluwatar.doublebuffer;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
/**
* FrameBuffer implementation class.
*/
public class FrameBuffer implements Buffer {
public static final int WIDTH = 10;
public static final int HEIGHT = 8;
private Pixel[] pixels = new Pixel[WIDTH * HEIGHT];
public FrameBuffer() {
clearAll();
}
@Override
public void clear(int x, int y) {
pixels[getIndex(x, y)] = Pixel.WHITE;
}
@Override
public void draw(int x, int y) {
pixels[getIndex(x, y)] = Pixel.BLACK;
}
@Override
public void clearAll() {
for (var i = 0; i < pixels.length; ++i) {
pixels[i] = Pixel.WHITE;
}
}
@Override
public Pixel[] getPixels() {
return pixels;
}
private int getIndex(int x, int y) {
return x + WIDTH * y;
}
}

View File

@ -0,0 +1,39 @@
/**
* The MIT License
* Copyright (c) 2014-2016 Ilkka Seppälä
* <p>
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
* <p>
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
* <p>
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*/
package com.iluwatar.doublebuffer;
/**
* Pixel enum. Each pixel can be white (not drawn) or black (drawn).
*/
public enum Pixel {
WHITE(0),
BLACK(1);
private int color;
Pixel(int color) {
this.color = color;
}
}

View File

@ -0,0 +1,86 @@
/**
* The MIT License
* Copyright (c) 2014-2016 Ilkka Seppälä
* <p>
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
* <p>
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
* <p>
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*/
package com.iluwatar.doublebuffer;
import org.apache.commons.lang3.tuple.Pair;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.util.List;
/**
* Scene class. Render the output frame.
*/
public class Scene {
private static final Logger LOGGER = LoggerFactory.getLogger(Scene.class);
private Buffer[] frameBuffers;
private int current;
private int next;
/**
* Constructor of Scene.
*/
public Scene() {
frameBuffers = new FrameBuffer[2];
frameBuffers[0] = new FrameBuffer();
frameBuffers[1] = new FrameBuffer();
current = 0;
next = 1;
}
/**
* Draw the next frame.
* @param coordinateList list of pixels of which the color should be black
*/
public void draw(List<Pair<Integer, Integer>> coordinateList) {
LOGGER.info("Start drawing next frame");
LOGGER.info("Current buffer: " + current + " Next buffer: " + next);
frameBuffers[next].clearAll();
for (Pair<Integer, Integer> coordinate : coordinateList) {
var x = coordinate.getKey();
var y = coordinate.getValue();
frameBuffers[next].draw(x, y);
}
LOGGER.info("Swap current and next buffer");
swap();
LOGGER.info("Finish swapping");
LOGGER.info("Current buffer: " + current + " Next buffer: " + next);
}
public Buffer getBuffer() {
LOGGER.info("Get current buffer: " + current);
return frameBuffers[current];
}
private void swap() {
current = current ^ next;
next = current ^ next;
current = current ^ next;
}
}

View File

@ -0,0 +1,39 @@
/**
* The MIT License
* Copyright (c) 2014-2016 Ilkka Seppälä
* <p>
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
* <p>
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
* <p>
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*/
package com.iluwatar.doublebuffer;
import org.junit.Test;
/**
* App unit test.
*/
public class AppTest {
@Test
public void testMain() {
String[] args = {};
App.main(args);
}
}

View File

@ -0,0 +1,97 @@
/**
* The MIT License
* Copyright (c) 2014-2016 Ilkka Seppälä
* <p>
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
* <p>
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
* <p>
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*/
package com.iluwatar.doublebuffer;
import org.junit.Assert;
import org.junit.Test;
/**
* FrameBuffer unit test.
*/
public class FrameBufferTest {
@Test
public void testClearAll() {
try {
var field = FrameBuffer.class.getDeclaredField("pixels");
Pixel[] pixels = new Pixel[FrameBuffer.HEIGHT * FrameBuffer.WIDTH];
for (int i = 0; i < pixels.length; ++i) {
pixels[i] = Pixel.WHITE;
}
pixels[0] = Pixel.BLACK;
var frameBuffer = new FrameBuffer();
field.setAccessible(true);
field.set(frameBuffer, pixels);
frameBuffer.clearAll();
Assert.assertEquals(Pixel.WHITE, frameBuffer.getPixels()[0]);
} catch (NoSuchFieldException | IllegalAccessException e) {
Assert.fail("Fail to modify field access.");
}
}
@Test
public void testClear() {
try {
var field = FrameBuffer.class.getDeclaredField("pixels");
Pixel[] pixels = new Pixel[FrameBuffer.HEIGHT * FrameBuffer.WIDTH];
for (int i = 0; i < pixels.length; ++i) {
pixels[i] = Pixel.WHITE;
}
pixels[0] = Pixel.BLACK;
var frameBuffer = new FrameBuffer();
field.setAccessible(true);
field.set(frameBuffer, pixels);
frameBuffer.clear(0, 0);
Assert.assertEquals(Pixel.WHITE, frameBuffer.getPixels()[0]);
} catch (NoSuchFieldException | IllegalAccessException e) {
Assert.fail("Fail to modify field access.");
}
}
@Test
public void testDraw() {
var frameBuffer = new FrameBuffer();
frameBuffer.draw(0, 0);
Assert.assertEquals(Pixel.BLACK, frameBuffer.getPixels()[0]);
}
@Test
public void testGetPixels() {
try {
var field = FrameBuffer.class.getDeclaredField("pixels");
Pixel[] pixels = new Pixel[FrameBuffer.HEIGHT * FrameBuffer.WIDTH];
for (int i = 0; i < pixels.length; ++i) {
pixels[i] = Pixel.WHITE;
}
pixels[0] = Pixel.BLACK;
var frameBuffer = new FrameBuffer();
field.setAccessible(true);
field.set(frameBuffer, pixels);
Assert.assertEquals(pixels, frameBuffer.getPixels());
} catch (NoSuchFieldException | IllegalAccessException e) {
Assert.fail("Fail to modify field access.");
}
}
}

View File

@ -0,0 +1,74 @@
/**
* The MIT License
* Copyright (c) 2014-2016 Ilkka Seppälä
* <p>
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
* <p>
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
* <p>
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*/
package com.iluwatar.doublebuffer;
import org.junit.Assert;
import org.junit.Test;
import java.lang.reflect.Field;
import java.util.ArrayList;
/**
* Scene unit tests.
*/
public class SceneTest {
@Test
public void testGetBuffer() {
try {
var scene = new Scene();
var field1 = Scene.class.getDeclaredField("current");
field1.setAccessible(true);
field1.set(scene, 0);
FrameBuffer[] frameBuffers = new FrameBuffer[2];
FrameBuffer frameBuffer = new FrameBuffer();
frameBuffer.draw(0, 0);
frameBuffers[0] = frameBuffer;
var field2 = Scene.class.getDeclaredField("frameBuffers");
field2.setAccessible(true);
field2.set(scene, frameBuffers);
Assert.assertEquals(frameBuffer, scene.getBuffer());
} catch (NoSuchFieldException | IllegalAccessException e) {
Assert.fail("Fail to access private field.");
}
}
@Test
public void testDraw() {
try {
var scene = new Scene();
var field1 = Scene.class.getDeclaredField("current");
var field2 = Scene.class.getDeclaredField("next");
field1.setAccessible(true);
field1.set(scene, 0);
field2.setAccessible(true);
field2.set(scene, 1);
scene.draw(new ArrayList<>());
Assert.assertEquals(1, field1.get(scene));
Assert.assertEquals(0, field2.get(scene));
} catch (NoSuchFieldException | IllegalAccessException e) {
Assert.fail("Fail to access private field");
}
}
}

View File

@ -183,6 +183,7 @@
<module>data-locality</module>
<module>subclass-sandbox</module>
<module>circuit-breaker</module>
<module>double-buffer</module>
</modules>
<repositories>