简单工厂

接口类:

packagecom.jerry.design.simpleFactory.imp;


/**

*

*@authorjerry

*

*/

publicinterfaceinterfaceTest {

publicvoidtest(String name);


}


实现类A:

packagecom.jerry.design.simpleFactory.impl;


importcom.jerry.design.simpleFactory.imp.interfaceTest;


/**

*

*@authorjerry

*

*/

publicclassImplAimplementsinterfaceTest {

publicvoidtest(String name){

System.out.println(" my ImplA name is:"+name);

}


}


实现类B:

packagecom.jerry.design.simpleFactory.impl;


importcom.jerry.design.simpleFactory.imp.interfaceTest;


/**

*

*@authorjerry

*

*/

publicclassImplBimplementsinterfaceTest {

publicvoidtest(String name){

System.out.println(" my ImplB name is:"+name);

}


}


工厂类:

packagecom.jerry.design.simpleFactory.factory;


importcom.jerry.design.simpleFactory.imp.interfaceTest;

importcom.jerry.design.simpleFactory.impl.ImplA;

importcom.jerry.design.simpleFactory.impl.ImplB;


publicclassFactory {

publicstaticinterfaceTest createImp(inttype){

interfaceTest test =null;

if(type==1){

test = (interfaceTest)newImplA();

}elseif(type==2){

test = (interfaceTest)newImplB();

}

returntest;

}


}


测试类:

packagecom.jerry.design.simpleFactory.factory;


importcom.jerry.design.simpleFactory.imp.interfaceTest;


publicclassTest {


publicstaticvoidmain(String[] args) {

interfaceTest test = Factory.createImp(1);

test.test(" i am jerry!");// my ImplA name is: i amjerry!

test = Factory.createImp(2);

test.test(" i am jerry!");// my ImplB name is: i amjerry!

}

}



总结:简单工厂其实就是要选择实现的类而已。

你可能感兴趣的:(简单工厂)