java 工廠方法詳解及實例代碼
更新時間:2017年01月25日 09:45:10 投稿:lqh
這篇文章主要介紹了java 工廠方法詳解及實例代碼的相關資料,需要的朋友可以參考下
工廠方法概述
工廠方法模式中抽象工廠類負責定義創(chuàng)建對象的接口,具體對象的創(chuàng)建工作由繼承抽象工廠的具體類實現。
優(yōu)點
客戶端不需要在負責對象的創(chuàng)建,從而明確了各個類的職責,如果有新的對象增加,只需要增加一個具體的類和具體的工廠類即可,不影響已有的代碼,后期維護容易,增強了系統的擴展性
缺點
需要額外的編寫代碼,增加子工作量
public class IntegerDemo { public static void main(String[] args) { Factory factory = new DogFactory(); Animal animal = factory.createAnimal(); animal.eat(); factory = new CatFactory(); animal = factory.createAnimal(); animal.eat(); } } abstract class Animal {// 抽象類 public abstract void eat(); } class Dog extends Animal {// 狗 public void eat() { System.out.println("a dog is eatting."); } } class Cat extends Animal {// 貓 public void eat() { System.out.println("a cat is eatting."); } } interface Factory {// 接口 public abstract Animal createAnimal(); } class DogFactory implements Factory {// 實現接口 public Animal createAnimal() { return new Dog(); } } class CatFactory implements Factory {// 實現接口 public Animal createAnimal() { return new Cat(); } }
感謝閱讀,希望能幫助到大家,謝謝大家對本站的支持!