java設計模式——抽象Factory 方法

來源:互聯網
上載者:User

說明:什麼使用我們可以使用抽象Factory 方法?怎麼使用抽象Factory 方法

應用情境:當我們建立的兩個類之間有組合關係的時候,比如說學校、老師、學生。這那個之間的關係是:學校可以使一中、二中、三中。老師可以是一中老師、二中老師。同樣,學生也可以使一中學生,二中學生。如果以後多一個三中的話,還有三中老師,三中學生。

定義:

  老師類:

  學生類:

               一中

                       一中老師

                       一中學生

              二中

                      二中老師

                      二中學生

                           學校工廠類(可以生產一中、二中)

具體實現:

        

public class Student { public void  showStudent(){ System.out.println("student..."); } }public class  Teacher { public void  showTeacher(){ System.out.println("teacher..."); } }

public class StudentFactory  {public static Student getStudent(){return new Student();}}public class TeacherFactory {public static Teacher getTeacher(){return new Teacher();}}public interface AbstractoFactor {Student getStudent();Teacher getTeacher();}

public interface ISchool {public abstract Student getStudent();public abstract Teacher getTeacher();}public class OneSchool implements AbstractoFactor, ISchool {public Student getStudent() {System.out.println("建立一中學生");return StudentFactory.getStudent();}public Teacher getTeacher() {System.out.println("建立一中老師");return TeacherFactory.getTeacher();}}public class ThreeSchool implements AbstractoFactor {public Student getStudent() {System.out.println("建立三中學生");return StudentFactory.getStudent();}public Teacher getTeacher() {System.out.println("建立三中老師");return TeacherFactory.getTeacher();}}public class TwoSchool implements AbstractoFactor {public Student getStudent() {System.out.println("建立二中學生");return StudentFactory.getStudent();}public Teacher getTeacher() {System.out.println("建立二中老師");return TeacherFactory.getTeacher();}}

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.