Transforming Conditionals to Polymorphism
I'm refactoring some code in project whilst reading Object-Oriented Reengineering Patterns specifically the section on "Transforming Conditionals to Polymorphism". So the current code base has constant that is referencing a factory class that which returns a bitmap based on displayWidth & displayHeight. To achieve this do I need to create two new classes, with each representing the differing screenWidth and screenHeight ? I'm a litte lost as to whats the best method of achieving polymorphism in this case.
public static final Bitmap TICKER_BACKGROUND_IMAGE = ImageFactory.getFooterBitmap();
Method in ImageFactory -
public class ImageFactory {
private static int displayWidth;
private static int displayHeight;
static {
display开发者_StackOverflow社区Width = 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");
}
}
}
I would take all it arguments as parameters. Don't use static variables as argument if you can.
public static Bitmap getFooterBitmap(int width, int height){
String filename = width == 360 && height == 480 ? "360x480" : "320x240";
return Bitmap.getBitmapResource(filename+"/footer_bp.png);
}
Using polymorphism is a good idea but not the best solution in every situation.
Another approach might be to see if the size is available and use a fall back position.
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;
}
Don't reference the widths in code, instead get the potential filename from the display size.
String filename = width + "x" + height
Now look for file of those particular dimensions. If it exists, use it, otherwise fall back on 320x240.
This way you don't have to keep your code in sync with the list of files.
精彩评论