写了一个简单的工厂模式,两个类,对应两个接口,一个类工厂,一个调用,总共6个类。
具体如下:
ClassA, ClassB 是两个类,Interface_A, Interface_B 是对应的两个接口,主要代码如下:
- public class ClassA implements Interface_A {
- public void testa() {
- System.out.println("ClassA");
- }
- }
- public interface Interface_A {
- public void testa();
- }
- public class ClassB implements Interface_B {
- public void testb() {
- System.out.println("Classb");
- }
- }
- public interface Interface_B {
- public void testb();
- }
工厂类如下所示:
- public class factory {
- private String classname = "";
- public String getClassname() {
- return classname;
- }
- public void setClassname(String classname) {
- this.classname = classname;
- }
- public factory() {
- }
- public Interface_A GetInterface_A() {
- Class t = null;
- try {
- t = Class.forName(classname);
- } catch (ClassNotFoundException e) {
- // TODO Auto-generated catch block
- e.printStackTrace();
- }
- try {
- return (Interface_A) t.newInstance();
- } catch (InstantiationException e) {
- // TODO Auto-generated catch block
- e.printStackTrace();
- } catch (IllegalAccessException e) {
- // TODO Auto-generated catch block
- e.printStackTrace();
- }
- return null;
- }
- public Interface_B GetInterface_B() {
- Class t = null;
- try {
- t = Class.forName(classname);
- } catch (ClassNotFoundException e) {
- // TODO Auto-generated catch block
- e.printStackTrace();
- }
- try {
- return (Interface_B) t.newInstance();
- } catch (InstantiationException e) {
- // TODO Auto-generated catch block
- e.printStackTrace();
- } catch (IllegalAccessException e) {
- // TODO Auto-generated catch block
- e.printStackTrace();
- }
- return null;
- }
- }
调用类如下,在其中增加了 main 函数,方便测试:
- /**
- *
- */
- /**
- * @author wanghq
- * @version 1.0.0
- *
- */
- public class main {
- /**
- * @param args
- */
- public static void main(String[] args) {
- // TODO Auto-generated method stub
- factory f = new factory();
- f.setClassname("ClassA");
- Interface_A ia = f.GetInterface_A();
- ia.testa();
- f.setClassname("ClassB");
- Interface_B ib = f.GetInterface_B();
- ib.testb();
- }
- }
输出如下:
ClassA
Classb