设计模式之-工厂方法-FactoryMethod
定义一个用于创建对象的接口,让子类决定实例化哪一个类。FactoryMethod使一个类的实例化延迟到其子类。
?
适用性:
1.当一个类不知道它所必须创建的对象的类的时候。
2.当一个类希望由它的子类来指定它所创建的对象的时候。
3.当类将创建对象的职责委托给多个帮助子类中的某一个,并且你希望将哪一个帮助子类是代理者这一信息局部化的时候。
?
?
package pack.java.iworkfactory;public interface IWork {/** * 开始工作方法; */public void doWork();}
?
?
?
package pack.java.iworkfactory;public interface IWorkFactory {/** * 获取工作; * @return */public IWork getWork();}
?
?
package pack.java.workfactoryimpl;import pack.java.iworkfactory.IWork;import pack.java.iworkfactory.IWorkFactory;public class StudentFactory implements IWorkFactory{public IWork getWork() {// TODO Auto-generated method stubreturn new StudentWork();}}
?
?
package pack.java.workfactoryimpl;import pack.java.iworkfactory.IWork;public class StudentWork implements IWork {public void doWork() {// TODO Auto-generated method stubSystem.out.println("学生做作业!");}}
?
?
package pack.java.workfactoryimpl;import pack.java.iworkfactory.IWork;import pack.java.iworkfactory.IWorkFactory;public class TeacherFactory implements IWorkFactory{public IWork getWork() {// TODO Auto-generated method stubreturn new TeacherWork();}}
?
?
package pack.java.workfactoryimpl;import pack.java.iworkfactory.IWork;public class TeacherWork implements IWork {public void doWork() {// TODO Auto-generated method stubSystem.out.println("老师批改作业!");}}
?
?
package pack.java.testfactorymethod;import pack.java.iworkfactory.IWorkFactory;import pack.java.workfactoryimpl.StudentFactory;import pack.java.workfactoryimpl.TeacherFactory;public class TestFactoryMethod {/** * @param args */public static void main(String[] args) {// TODO Auto-generated method stub//学生工厂方法;IWorkFactory studentFactory = new StudentFactory();//学生开始工作;studentFactory.getWork().doWork();//老师工厂方法;IWorkFactory teacherFactory = new TeacherFactory();//老师开始工作;teacherFactory.getWork().doWork();}}
?
?
?
运行结果:
学生做作业!
老师批改作业!