我想在我的应用程序中计算多个事物,并将其值保存到android sharedpreferences。一切正常,但是总体上我对课程设计不满意。
非常简单的抽象类。类参数用于命名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);
}
}
到目前为止,我已经有5个类从Counter继承了所有相同的内容。
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;
}
}
我有一些计数器,我想从不同的类中调用并在其中增加(例如CounterAPICall或CounterOnResumeCallExample)。使用此代码可以正常工作。
最佳答案
此代码对于检索适当的计数器可能很有用:
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;
}
}
在这种情况下,Counter不是抽象类。出于任何目的,您都可以为Counter指定一个名称,该名称存储在地图中。