首先 定义一接口
package com.org; public interface SampleInterface { public void print(String s); }
定义两个接口的实现类
package com.org.impl; import com.org.SampleInterface; public class ImpleOne implements SampleInterface { @Override public void print(String s) { // TODO Auto-generated method stub System.out.println(s); } }
package com.org.impl; import com.org.SampleInterface; public class ImpleTwo implements SampleInterface { @Override public void print(String s) { // TODO Auto-generated method stub System.out.println(s); } }
定义一工厂类 实现对象的创建
package com.org.factory; import com.org.SampleInterface; import com.org.impl.ImpleOne; import com.org.impl.ImpleTwo; public class Factory { public static SampleInterface getImple(String str){ if("one".equals(str)){ return new ImpleOne(); } else{ return new ImpleTwo(); } } }
测试类
package com.org.test; import com.org.SampleInterface; import com.org.factory.Factory; public class Test { /** * @param args */ public static void main(String[] args) { // TODO Auto-generated method stub SampleInterface face = Factory.getImple("one"); face.print("Hello World"); face = Factory.getImple("two"); face.print("wa wa"); } }
原创文章,作者:奋斗,如若转载,请注明出处:https://blog.ytso.com/14360.html