首页 > 代码库 > 接口之工厂方法的设计模式

接口之工厂方法的设计模式

1 定义一个用于创建对象的接口,让子类决定实例化哪一个类,FactoryMethod使一个类的实例化延迟到子类

package p1;public class TestFactory {    public static void main(String[] args) {        IWorkFactory i = new TeacherWorkFactory();        i.getWork().doWork();     //Teacher is working        IWorkFactory i2 = new StudentWorkFactory();        i2.getWork().doWork();    //Student is working    }}interface IWorkFactory {    public abstract Work getWork();}class TeacherWorkFactory implements IWorkFactory {    @Override    public Work getWork() {        return new TeacherWork();    }}class StudentWorkFactory implements IWorkFactory {    @Override    public Work getWork() {        return new StudentWork();    }}interface Work {    public abstract void doWork();}class TeacherWork implements Work {    public void doWork() {        System.out.println("Teacher is working");    }}class StudentWork implements Work {    public void doWork() {        System.out.println("Student is working");    }}

接口之工厂方法的设计模式