?£ê?à′éè???a???ó?ú£o
class DataInfo {}
interface Local {
????DataInfo[] loadDB(String filename);
}
interface Remote extends Local{
??????void connect2WWW(String url);
}
class LocalMode implements Local {
??public DataInfo[] loadDB(String name) {
????System.out.print("Load from a local database ");
????return null;
??}
}
class RemoteMode implements Remote {
??public void connect2WWW(String url) {
????System.out.println("Connect to a remote site ");
??}
????//????ê???loadDB·?·¨μ?áíò???êμê???public DataInfo[] loadDB(String name) {
???? System.out.println("Load from a remote database ");
???? return null;
??}
}
????//?????íê?3é?ó1¤3§á?interface ConnectionFactory {
??Local getLocalConnection();
??Remote getRemoteConnection();
}
class DataManager implements ConnectionFactory {
????boolean local = false;
????DataInfo[] data;
????//...
????public Local getLocalConnection() {
????????return new LocalMode();
????}
????public Remote getRemoteConnection() {
????????return new RemoteMode();
????}
????public??void loadData() {
???????? if(local){
????????????Local conn = getLocalConnection();
????????????data = conn.loadDB("db.db");
???????? }else {
????????????Remote conn = getRemoteConnection();
????????????conn.connect2WWW("www.some.where.com");
????????????data = conn.loadDB("db.db");
???????? }
???? }
???? // work on data
????public void setConnection(boolean b) {
?????? local = b;
????}
}
//ó?ò???2aê?·?·¨à′2aê?é?ê?μ?ààclass Test {
???? public static void main(String[] args) {
???????? DataManager dm = new DataManager();
???????? DataInfo[] di = null;
???????? String dbFileName = "db.db"$
???????? if (args.length == 1) {
???????????? //assume local is set to true
???????? dm.setConnection(true);
???????????? LocalMode lm = (LocalMode)dm.getLocalConnection();
???????? di = lm.loadDB(dbFileName);
???????? } else {??
?????????? //Note: dm.local = false is default setting
?????????? RemoteMode rm = (RemoteMode)dm.getRemoteConnection();
?????????? rm.connect2WWW("www.javacamp.org/db/");
?????????? di = rm.loadDB(dbFileName);
???????? }
???????? //ò????í?éò?????ê1ó?ò?ì×·?·¨à′′|àíó?é?ê?·?·¨?ó??μ?êy?Y
???????? //Like di.find(), di.search() etc.
???? //′ó′?£?2?Dè?ù?aêy?Y?aμ?á??ó??μ£D?
???? }
}
????ê?′ó?üá?DDμ÷ó?Testàà????DD2aê?μ??é??£?×¢òa£?òò2?êyμ?2?í?£???3???μ?2?í???DD?á1??£
C:> java Test
Connect to a remote site
Load from a remote database
C:> java Test local
Load from a local database
C:??Comma
?a?ùμ?éè??ò?°??áó??ú?úSun1????a·¢è??±μ?è??¤??ê??D?£è?1????éò?′ó2?í?μ?μ?·??ó??êy?Y£?????Dè?úconnection1¤3§?ó?ú?D?óè?ò???·?·¨£??úo?êêμ?????êμê??ü£???2?Dè??????3ìDò?á11óD??oáμ???±??£ |