Search code examples
javainheritanceabstract-class

Simplify multiple inheriting classes (with all same content) of abstract class


I like to count multiple things in my app and save the value to android sharedpreferences. Everything works, but I am not satisfied with the class design in general.

Very simple abstract class. Class parameter is used to name keys in sharedPreferences.

public abstract class Counter {

    private Context mContext;
    private Class mClass;

    Counter(Class myClass, Context context) {
        this.mClass = myClass;
        this.mContext = context;
    }

    public Integer getValue() {
        return PrefManager.with(mContext).getInt(mClass.getName(), 0);
        //return UniversalPreferences.getInstance().get(counterName, 1);
    }

    public void increment() {
        PrefManager.with(mContext).save(mClass.getName(), getValue() + 1);
        //UniversalPreferences.getInstance().put(counterName, getCurrentValue(counterName) + 1);
    }
}

So far I have already 5 classes inheriting from Counter with all the same content.

public class CounterAppLaunch extends Counter {

    @SuppressLint("StaticFieldLeak")
    private static CounterAppLaunch instance;

    private CounterAppLaunch(Context context) {
        super(CounterAppLaunch.class, context);
    }

    public static CounterAppLaunch getInstance(Context context) {
        if(CounterAppLaunch.instance == null) {
            CounterAppLaunch.instance = new CounterAppLaunch(context);
        }
        return CounterAppLaunch.instance;
    }
}

I have counters I like to call from different classes and increment there (eg. CounterAPICall or CounterOnResumeCallExample). Which works with this code just fine.


Solution

  • This code might be useful to retrieve an appropriate counter:

    public Counter{
        private int count;
    
        public Counter(){
            count = 0;
        }
    
        public int getValue(){
            return count;
        }
    
        public void increment(){
            counter++;
        }
    }
    
    public CounterStorage(){
        private static HashMap<String, Counter> counterMap = new HashMap<>();
    
        public static Counter getInstance(String str){
            if (counterMap.containsKey(str)) return counterMap.get(str);
    
            Counter newCounter = new Counter();
            counterMap.add(str, newCounter);
            return newCounter;
    
        }
    }
    

    In this case, Counter isn't an abstract class. For any purpose, you can give a Counter a name, which is stored in the map.