jeudi 22 octobre 2020

Java - Polymorphism implement forced common alterations to child's fields

What's the best design pattern to force children of an abstract class to call a function defined in the abstract class that alters the value of its implemented abstract variables?


The problem:

I want to scale my bitmaps according to the screen size to keep the ratio. I want to avoid having multiple abstract variables that are essentially assigned the same way. For example in this case widthScale * width will scale the width when assigned to the width. If I create an abstract method named scaleWidth(), though it would imply to the user of the class that they should implement such functionality, it'd cause a repetitious implementation of the same method throughout the codebase.

Also can't have a scaledWidth variable in the abstract class that multiplies 2 abstract variables since parent's fields are initialized before the childrens'

Pseudocode example:

Abstract Class Image
{
  abstract int width;

}

Class Apple extends Image
{
  override int width = 100 * StaticAppClass.scaleFactorWidth;

}

Class Banana extends Image
{
  override int width = 50 * StaticAppClass.scaleFactorWidth;
}

So as you can see every time the programmer has to multiply the width with the StaticAppClass.scaleFactorWidth. Not only it's inconvenient also it's not explicit. Meaning, the programmer wouldn't even know he has to do that

Aucun commentaire:

Enregistrer un commentaire