关于重构的一点练习

    科技2022-07-20  101

    我们总是在重复的造轮子。 2019年下半年就想要写一个斗地主记牌器的Java程序,结果到了现在也是仅仅完成了截图的功能。

    分享这篇博客主要目的是分享一下关于重构的一点实践成果,顺便贴上代码。

    早期时为了找屏幕截图并获取像素点的Java源码,很难找,最后发现了一位博主写的代码,结果结构比较混乱,非常难读(也许是我技术不到位)。月前看了本关于重构的书,前几天又想要写斗地主记牌器的程序,找呀找终于又找到了它,然后又是无从下手,于是练习了一下重构。项目是使用eclipse编写的代码,用Git建立了一个本地仓库(就在项目文件夹下的.git文件夹里)保存了每一次修改,由于英语水平有限,commit message中夹杂了中文,可能有些语句不太通顺,欢迎大家评论区吐槽。

    代码的项目文件夹我已上传到资源文件中,在文末会附上下载链接,当然是免费的。

    下面就是附上的部分源码了,源码中注释基本没有,都是写在了commit message中,欢迎在eclipse中使用Git与我一起开启重构之旅!

    下面这个类是实现屏幕截图的类,是重构后的结果。

    package qdu.lf.get; import java.awt.AWTException; import java.awt.HeadlessException; import java.awt.Rectangle; import java.awt.Robot; import java.awt.Toolkit; import java.awt.image.BufferedImage; import java.io.File; import java.io.IOException; import javax.imageio.ImageIO; public class ScreenShot { private final static String defaultImageFormater = "png"; private BufferedImage bufferedImage; private static String path = "d:"; private static String name = "temp.png"; public static void setPath(String path) { ScreenShot.path = path; } public static void setName(String name) { ScreenShot.name = name; } public ScreenShot() { File tempFile = new File(path, name); setBufferedImage(); saveToFile(tempFile); } public ScreenShot(int x, int y, int w, int h) { File tempFile = new File(path, name); setBufferedImage(); bufferedImage = bufferedImage.getSubimage(x, y, w, h); saveToFile(tempFile); } private void setBufferedImage() { try { bufferedImage = new Robot().createScreenCapture(new Rectangle(Toolkit.getDefaultToolkit().getScreenSize())); } catch (HeadlessException | AWTException e) { e.printStackTrace(); } } private void saveToFile(File tempFile) { try { ImageIO.write(bufferedImage, defaultImageFormater , tempFile); } catch (IOException e) { e.printStackTrace(); } } }

    重构是自动化测试驱动的,当然要有一个测试类来保证每一次修改都不会破坏源代码的功能了,不过测试还不太会,只是简单加了几个测试类,见谅见谅。

    package qdu.lf.get; import org.junit.Test; public class ScreenShotTest { @Test public void test_nonparametric_construction_method_ScreenShot() { new ScreenShot(); } @Test public void test_construction_method_ScreenShot_by_method_setPath_and_setName() { ScreenShot.setName("temp1.png"); ScreenShot.setPath("d:"); new ScreenShot(); } @Test public void test_construction_method_ScreenShot_with_parameters_x_y_w_h_about_subimage() { ScreenShot.setName("temp2.png"); new ScreenShot(700, 600, 300, 100); } }

    最后还有一个类,主要是建了一个线程类持续截图的,很简单。

    package qdu.lf.get; public class ContinuedRunningScreenShot { public static void main(String[] args) throws InterruptedException { Thread thread = new Thread(); thread.start(); for (int i=0; i<20; i++) { Thread.sleep(100); // ScreenShot.setName("temp-"+i+".png"); new ScreenShot(); } } }

    补充一句,截图后的图片在d盘,是png图片文件。

    最后,资源审核还没通过,通过后会附上下载链接。或者可以直接在本账号分享的资源中查找。


    资源审核已通过,以下是下载链接:

    下载链接,点我跳转

    Processed: 0.012, SQL: 8