Interface Definition
package com.ttjslbz.factory;public interface Api {void functionA();}
Define implementation
public class ImplA implements Api {@Overridepublic void functionA() {// TODO Auto-generated method stubSystem.out.print("This is implement A for Api");}}
Define implementation B
public class ImplB implements Api {@Overridepublic void functionA() {// TODO Auto-generated method stubSystem.out.print("This is implement B for Api");}}
Factory
Public class factory {// pre-load the configuration file Private Static Properties P to be read; static {inputstream in = factory. class. getresourceasstream ("factory. properties "); P = new properties (); try {P. load (in);} catch (ioexception e) {// todo auto-generated catch blocke. printstacktrace ();} finally {try {In. close ();} catch (ioexception e) {e. printstacktrace () ;}} public static API creatapi (string propertie) {apiapi = NULL; try {API = (API) class. forname (P. getproperty (propertie )). newinstance ();} catch (instantiationexception e) {e. printstacktrace ();} catch (illegalaccessexception e) {// todo auto-generated catch blocke. printstacktrace ();} catch (classnotfoundexception e) {// todo auto-generated catch blocke. printstacktrace ();} return API ;}}
Client
public class Client {public static void main(String[] args) {Api apiA = Factory.creatApi("IMPLEMENTA");apiA.functionA();Api apiB= Factory.creatApi("IMPLEMENTB");apiB.functionA();Api apiC = Factory.creatApi("IMPLEMENTC");apiC.functionA();}}