Java工具集-數學(反比例函數)
- 2019 年 10 月 26 日
- 筆記
簡單工具類
寫作初衷:由於日常開發經常需要用到很多工具類,經常根據需求自己寫也比較麻煩 網上好了一些工具類例如commom.lang3或者hutool或者Jodd這樣的開源工具,但是 發現他們之中雖然設計不錯,但是如果我想要使用,就必須要引入依賴並且去維護依賴,有些 甚至會有存在版本編譯不通過問題,故此想要寫作一個每個類都可以作為獨立工具類使用 每個使用者只需要複製該類,到任何項目當中都可以使用,所以需要尊從以下兩個原則才能 做到.在此誠邀各位大佬參與.可以把各自用過的工具,整合成只依賴JDK,每個類都能夠單獨 使用的工具.每個人當遇到業務需求需要使用的時候,只需要到這裡單獨拷貝一個即可使用. 拋棄傳統的需要引入依賴的煩惱.讓大家一起來解決你所面臨的業務問題吧!
介紹
遵從兩大原則
- 1.絕不依賴JDK以外的源碼
- 2.犧牲程式碼復用性,每個類都必須是單獨的組件,絕不互相引用,做到完全解耦
package *; import java.math.BigDecimal; /** * @program: simple_tools * @description: 數學(反比例函數) * @author: Mr.chen * @create: 2019-10-24 22:10 **/ public class InverseFunction { // y = k/x //斜率 private double k = 1; private static InverseFunction instance; private InverseFunction(){}; static{ if(instance == null){ synchronized (InverseFunction.class){ if(instance == null){ instance = new InverseFunction(); } } } } /** * 創建反比例函數 * @param k */ public static void init(double k){ if(k == 0){ throw new RuntimeException("param k is not be zero"); } instance.setK(k); } /** * 使用一個點初始化反比例函數 * @param point */ public static void init(Point point){ if(point == null){ throw new RuntimeException("point k is not be null"); } double x = point.getX(); double y = point.getY(); double k = new BigDecimal(x / y).setScale(2, BigDecimal.ROUND_HALF_UP).doubleValue(); instance.setK(k); } /** * 判斷點point是否在線上 * @param point * @return */ public static boolean isOnline(Point point){ if(point == null){ throw new RuntimeException("point is not be null !"); } double x = point.getX(); double y = point.getY(); return instance.getK() == x / y; } //點 public static class Point{ // x坐標 private double x; // y坐標 private double y; public Point(double x,double y){ this.x = x; this.y = y; } public double getX() { return x; } public void setX(double x) { this.x = x; } public double getY() { return y; } public void setY(double y) { this.y = y; } } public double getK() { return k; } public void setK(double k) { this.k = k; } }