package methodFactory;
public interface People {
void say();
}
package methodFactory;
public class Man implements People{
public void say() {
System.out.println("男人");
}
}
package methodFactory;
public class Woman implements People{
public void say() {
System.out.println("女人");
}
}
package methodFactory;
public interface PeopleFactory {
People create();
}
package methodFactory;
public class ManFactory implements PeopleFactory{
public People create() {
return new Man();
}
}
package methodFactory;
public class WomanFactory implements PeopleFactory{
public People create() {
return new Woman();
}
}
package methodFactory;
public class Test {
public static void main(String[] args) {
PeopleFactory manf= new ManFactory();
People man = manf.create();
man.say();
PeopleFactory wf= new WomanFactory();
People w = wf.create();
w.say();
}
}
好处是新增加的子类不会影响以前的实现,代码的扩展性好。