您好,登錄后才能下訂單哦!
這篇文章給大家分享的是有關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進行舉報,并提供相關證據,一經查實,將立刻刪除涉嫌侵權內容。