abstract class Person { public abstract void sayHello(); } class GDPerson extends Person { public void sayHello() { System.out.println("我是廣東人"); } } class BJPerson extends Person { public void sayHello() { System.out.println("我是北京人"); } } class PersonFactory { static final int GD=1; static final int BJ=2; public static Person createPerson(int area) { switch (area) { case GD: return new GDPerson(); case BJ: return new BJPerson(); default: return null; } } } public class Demo5 { public static void main(String[] args) { Person gdPerson=PersonFactory.createPerson(PersonFactory.GD); gdPerson.sayHello(); Person bjPerson=PersonFactory.createPerson(PersonFactory.BJ); bjPerson.sayHello(); } }
調用者沒必要知道對象是如何建立的,只要傳入相應的參數就能夠html
可是,若是這個時候須要添加其餘的type,那麼就要增長case,也就是對設計完成的類進行修改,而這樣就違背了開放封閉原則設計模式
public interface PersonFactory { Person createPerson(); } class GDFactory implements PersonFactory { public Person createPerson() { return new GDPerson(); } } class BJFactory implements PersonFactory { public Person createPerson() { return new BJPerson(); } } public class Demo5 { public static void main(String[] args) { PersonFactory gdFactory=new GDFactory(); Person gdPerson=gdFactory.createPerson(); PersonFactory bjFactory=new BJFactory(); Person bjPerson=bjFactory.createPerson(); } }
abstract class Animal { public abstract void sayHello(); } class Cat extends Animal { public void sayHello() { System.out.println("瞄"); } } public interface Factory { Person createPerson(); Animal createAnimal(); } class Factory1 implements Factory { public Person createPerson() { return new BJPerson(); } public Animal createAnimal() { return new Cat(); } }
做者:jiajun 出處: http://www.cnblogs.com/-new/
本文版權歸做者和博客園共有,歡迎轉載,但未經做者贊成必須保留此段聲明,且在文章頁面明顯位置給出原文鏈接,不然保留追究法律責任的權利。若是以爲還有幫助的話,能夠點一下右下角的【推薦】,但願可以持續的爲你們帶來好的技術文章!想跟我一塊兒進步麼?那就【關注】我吧。設計