package com.jerry.design.factoryMethod.imp;
/**
*
* @author jerry
*
*/
public interface interfaceTest {
public void test(String name);
}
实现类A:
package com.jerry.design.factoryMethod.impl;
import com.jerry.design.factoryMethod.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.factoryMethod.impl;
import com.jerry.design.factoryMethod.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.factoryMethod.imp;
public abstract class abstractClass {
public void test(String name){
interfaceTest impl = getImpl();
impl.test(name);
}
public abstract interfaceTest getImpl() ;
}
子类A;
package com.jerry.design.factoryMethod.impl;
import com.jerry.design.factoryMethod.imp.abstractClass;
import com.jerry.design.factoryMethod.imp.interfaceTest;
public class ClassA extends abstractClass {
@Override
public interfaceTest getImpl() {
return new ImplA();
}
}
子类B:
package com.jerry.design.factoryMethod.impl;
import com.jerry.design.factoryMethod.imp.abstractClass;
import com.jerry.design.factoryMethod.imp.interfaceTest;
public class ClassB extends abstractClass {
@Override
public interfaceTest getImpl() {
return new ImplB();
}
}
测试类:
package com.jerry.design.factoryMethod.client;
import com.jerry.design.factoryMethod.imp.abstractClass;
import com.jerry.design.factoryMethod.impl.ClassA;
import com.jerry.design.factoryMethod.impl.ClassB;
public class Test{
public static void main(String[] args) {
abstractClass ac = new ClassA();
ac.test("yushh");
abstractClass ac2 = new ClassB();
ac2.test("yushh2");
// my ImplA name is:yushh
// my ImplB name is:yushh2
}
}
总结:分离出业务与创建,延迟实现。