您好,登录后才能下订单哦!
这篇文章给大家分享的是有关java如何实现抽象工厂模式Abstract Factory的内容。小编觉得挺实用的,因此分享给大家做个参考,一起跟随小编过来看看吧。
在工厂类模式中,如果需要新的类时,需要修改工厂类,这样显然不利于扩展。在抽象工厂模式中,需要扩展一个类时,不需要修改之前的代码就可以实现。
[java]view plain copy print?
/**
* Created by Administrator on 2016/11/18.
*/
public interface Worker {
public void work();
}
[java]view plain copy print?
public interface Provider{
public Worker produce();
}
[java]view plain copy print?
public class Doctor implements Worker {
@Override
public void work() {
System.out.println("医生开始上班了");
}
}
[java]view plain copy print?
public class DoctorFactory implements Provider {
@Override
public Worker produce() {
return new Doctor();
}
}
[java]view plain copy print?
public class Student implements Worker {
@Override
public void work() {
System.out.println("学生开始上课了");
}
}
[java]view plain copy print?
public class StudentFactory implements Provider {
@Override
public Worker produce() {
return new Student();
}
}
[java]view plain copy print?
public class Teacher implements Worker {
@Override
public void work() {
System.out.println("教师开始教学了");
}
}
[java]view plain copy print?
public class TeacherFactory implements Provider {
@Override
public Worker produce() {
return new Teacher();
}
}
[java]view plain copy print?
public class Headmaster extends Teacher {
public void work(){
System.out.println("校长开始上班了");
}
}
[java]view plain copy print?
public class HeadmasterFactory implements Provider {
@Override
public Worker produce() {
return new Headmaster();
}
}
[java]view plain copy print?
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();
}
}
}
感谢各位的阅读!关于“java如何实现抽象工厂模式Abstract Factory”这篇文章就分享到这里了,希望以上内容可以对大家有一定的帮助,让大家可以学到更多知识,如果觉得文章不错,可以把它分享出去让更多的人看到吧!
免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。