packagecom.jerry.design.factoryMethod.imp;
/**
*
*@authorjerry
*
*/
publicinterfaceinterfaceTest {
publicvoidtest(String name);
}
实现类A:
packagecom.jerry.design.factoryMethod.impl;
importcom.jerry.design.factoryMethod.imp.interfaceTest;
/**
*
*@authorjerry
*
*/
publicclassImplAimplementsinterfaceTest {
publicvoidtest(String name){
System.out.println(" my ImplA name is:"+name);
}
}
实现类B:
packagecom.jerry.design.factoryMethod.impl;
importcom.jerry.design.factoryMethod.imp.interfaceTest;
/**
*
*@authorjerry
*
*/
publicclassImplBimplementsinterfaceTest {
publicvoidtest(String name){
System.out.println(" my ImplB name is:"+name);
}
}
抽象类:
packagecom.jerry.design.factoryMethod.imp;
publicabstractclassabstractClass {
publicvoidtest(String name){
interfaceTest impl = getImpl();
impl.test(name);
}
publicabstractinterfaceTest getImpl() ;
}
子类A;
packagecom.jerry.design.factoryMethod.impl;
importcom.jerry.design.factoryMethod.imp.abstractClass;
importcom.jerry.design.factoryMethod.imp.interfaceTest;
publicclassClassAextendsabstractClass {
@Override
publicinterfaceTest getImpl() {
returnnewImplA();
}
}
packagecom.jerry.design.factoryMethod.client;
importcom.jerry.design.factoryMethod.imp.abstractClass;
importcom.jerry.design.factoryMethod.impl.ClassA;
importcom.jerry.design.factoryMethod.impl.ClassB;
publicclassTest{
publicstaticvoidmain(String[] args) {
abstractClass ac =newClassA();
ac.test("yushh");
abstractClass ac2 =newClassB();
ac2.test("yushh2");
// my ImplA name is:yushh
// my ImplB name is:yushh2
}
}
总结:分离出业务与创建,延迟实现。