Context package com.jk.test.context; import com.jk.test.sharedpreferences.SharedPreferences; public abstract class Context { public abstract SharedPreferences getSharedPreferences(String name, int mode); } package com.jk.test.context; import java.util.HashMap; import com.jk.test.sharedpreferences.SharedPreferences; import com.jk.test.sharedpreferences.SharedPreferencesImpl; public class ContextImpl extends Context { private static final HashMap<String, SharedPreferencesImpl> sSharedPrefs = new HashMap<String, SharedPreferencesImpl>(); public ContextImpl() { super(); sSharedPrefs.put("name", new SharedPreferencesImpl(1)); } @Override public SharedPreferences getSharedPreferences(String name, int mode) { SharedPreferencesImpl sp; sp = sSharedPrefs.get(name); if (sp == null) { sp = new SharedPreferencesImpl(mode); sSharedPrefs.put(name, sp); return sp; } return sp; } } preferencemanager package com.jk.test.preferencemanager; import com.jk.test.context.Context; import com.jk.test.sharedpreferences.SharedPreferences; public class PreferenceManager { public static SharedPreferences getDefaultSharedPreferences(Context context){ return context.getSharedPreferences("name", 0); } } sharedpreferences package com.jk.test.sharedpreferences; public interface SharedPreferences { } package com.jk.test.sharedpreferences; public class SharedPreferencesImpl implements SharedPreferences { public SharedPreferencesImpl(int mode) { } @Override public String toString() { return "= " + SharedPreferencesImpl.class.getName().hashCode(); } //1914154876 //1914154876 } package com.jk.test; import com.jk.test.context.Context; import com.jk.test.context.ContextImpl; import com.jk.test.preferencemanager.PreferenceManager; import com.jk.test.sharedpreferences.SharedPreferences; public class Test { /** * @param args */ public static void main(String[] args) { Context c = new ContextImpl(); SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(c); System.out.println(prefs); } }
模拟Context调用
最新推荐文章于 2024-04-20 18:46:28 发布