在工厂类模式中,如果需要新的类时,需要修改工厂类,这样显然不利于扩展。在抽象工厂模式中,需要扩展一个类时,不需要修改之前的代码就可以实现。
看下简单的图例:
- /**
- * Created by Administrator on 2016/11/18.
- */
- public interface Worker {
- public void work();
- }
- public interface Provider{
- public Worker produce();
- }
- public class Doctor implements Worker {
- @Override
- public void work() {
- System.out.println("医生开始上班了");
- }
- }
- public class DoctorFactory implements Provider {
- @Override
- public Worker produce() {
- return new Doctor();
- }
- }
- public class Student implements Worker {
- @Override
- public void work() {
- System.out.println("学生开始上课了");
- }
- }
- public class StudentFactory implements Provider {
- @Override
- public Worker produce() {
- return new Student();
- }
- }
- public class Teacher implements Worker {
- @Override
- public void work() {
- System.out.println("教师开始教学了");
- }
- }
- public class TeacherFactory implements Provider {
- @Override
- public Worker produce() {
- return new Teacher();
- }
- }
- public class Headmaster extends Teacher {
- public void work(){
- System.out.println("校长开始上班了");
- }
- }
- public class HeadmasterFactory implements Provider {
- @Override
- public Worker produce() {
- return new Headmaster();
- }
- }
- public class Test {
- public static void main(String[] args) {
- Provider providers[] = {new DoctorFactory(), new StudentFactory(), new TeacherFactory(), new HeadmasterFactory()};
- for (Provider f : providers) {
- f.produce().work();
- }
- }
- }
来自 “ ITPUB博客 ” ,链接:http://blog.itpub.net/29876893/viewspace-2140452/,如需转载,请注明出处,否则将追究法律责任。
转载于:http://blog.itpub.net/29876893/viewspace-2140452/