gpt4 book ai didi

java - 将条件语句转换为多态性

转载 作者:行者123 更新时间:2023-12-02 00:41:34 25 4
gpt4 key购买 nike

我正在重构项目中的一些代码,同时阅读 Object-OrientedReengineering Patterns特别是“将条件转换为多态性”部分。因此,当前的代码库具有引用工厂类的常量,该工厂类返回基于 displayWidth 和 displayHeight 的位图。为了实现这一点,我是否需要创建两个新类,每个类代表不同的 screenWidth 和 screenHeight ?我对在这种情况下实现多态性的最佳方法有点迷失。

public static final Bitmap TICKER_BACKGROUND_IMAGE = ImageFactory.getFooterBitmap();

ImageFactory 中的方法 -

公共(public)类 ImageFactory {

private static int displayWidth;
private static int displayHeight;

static {
displayWidth = Display.getWidth();
displayHeight = Display.getHeight();
}

public static Bitmap getFooterBitmap(){

if(displayWidth == 360 && displayHeight == 480){
return Bitmap.getBitmapResource("360x480/footer_bg.png");
}
else {
return Bitmap.getBitmapResource("320x240/footer_bg.png");
}

}

}

最佳答案

我会将所有参数作为参数。如果可以的话,不要使用静态变量作为参数。

public static Bitmap getFooterBitmap(int width, int height){ 
String filename = width == 360 && height == 480 ? "360x480" : "320x240";
return Bitmap.getBitmapResource(filename+"/footer_bp.png);
}

使用多态性是一个好主意,但并不是在所有情况下都是最佳解决方案。

<小时/>

另一种方法可能是查看大小是否可用并使用回退位置。

public static Bitmap getFooterBitmap(int width, int height){ 
Bitmap bm = Bitmap.getBitmapResource(width+"x"+height+"/footer_bp.png);
if (bm == null)
bm = Bitmap.getBitmapResource("320x240/footer_bp.png);
return bm;
}

关于java - 将条件语句转换为多态性,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6227592/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com