package com.jerry.design.simpleFactory.imp;
/**
*
* @author jerry
*
*/
public interface interfaceTest {
public void test(String name);
}
实现类A:
package com.jerry.design.simpleFactory.impl;
import com.jerry.design.simpleFactory.imp.interfaceTest;
/**
*
* @author jerry
*
*/
public class ImplA implements interfaceTest {
public void test(String name){
System.out.println(" my ImplA name is:"+name);
}
}
实现类B:
package com.jerry.design.simpleFactory.impl;
import com.jerry.design.simpleFactory.imp.interfaceTest;
/**
*
* @author jerry
*
*/
public class ImplB implements interfaceTest {
public void test(String name){
System.out.println(" my ImplB name is:"+name);
}
}
工厂类:
package com.jerry.design.simpleFactory.factory;
import com.jerry.design.simpleFactory.imp.interfaceTest;
import com.jerry.design.simpleFactory.impl.ImplA;
import com.jerry.design.simpleFactory.impl.ImplB;
public class Factory {
public static interfaceTest createImp(int type){
interfaceTest test = null;
if(type==1){
test = (interfaceTest) new ImplA();
}else if(type==2){
test = (interfaceTest) new ImplB();
}
return test;
}
}
测试类:
package com.jerry.design.simpleFactory.factory;
import com.jerry.design.simpleFactory.imp.interfaceTest;
public class Test {
public static void main(String[] args) {
interfaceTest test = Factory.createImp(1);
test.test(" i am jerry!");// my ImplA name is: i am jerry!
test = Factory.createImp(2);
test.test(" i am jerry!");// my ImplB name is: i am jerry!
}
}
总结:简单工厂其实就是要选择实现的类而已。