When I’m working on a regional mobile app recently, I start to notice an useful usage of interface
when combine with Gradle Build Variants in Android Studio.
Firstly, I put an interface
in the main project.
public interface CurrencyFormatUtil {
String formatMoney(double number);
}
Then I add the Impl
class in both HongKong
& Malaysia
build variants with different implementation.
public class HongKongCurrencyFormatUtil implements CurrencyFormatUtil {
private static final String CURRENCY_SYMBOL = "HK$";
@Inject public HongKongCurrencyFormatUtil() {
}
@Override public String formatMoney(double number) {
return "HK$ 1.8 M";
}
}
public class MalaysiaCurrencyFormatUtil implements CurrencyFormatUtil {
private static final String CURRENCY_SYMBOL = "RM";
@Inject public MalaysiaCurrencyFormatUtil() {
}
@Override public String formatMoney(double number) {
return "RM 1,800,000";
}
}
With a little help from Google Dagger 2 dependency injection library, it will be able to return different currency format implementation base on build variant selection.
@Module
public class HongKongDaggerModule {
@Provides CurrencyFormatUtil provideCurrencyFormatUtil() {
return new HongKongCurrencyFormatUtil();
}
}
@Module
public class MalaysiaDaggerModule {
@Provides CurrencyFormatUtil provideCurrencyFormatUtil() {
return new MalaysiaCurrencyFormatUtil();
}
}
Lastly, I just need to inject
it in the main project.
public class MainActivity extends AppCompatActivity {
@Inject CurrencyFormatUtil currencyFormatUtil;
private void showContent() {
textView.setText(currencyFormatUtil.formatMoney(1800000.0));
}
}
That’s it.