工廠方法概述
工廠方法模式中抽象工廠類負責(zé)定義創(chuàng)建對象的接口,具體對象的創(chuàng)建工作由繼承抽象工廠的具體類實現(xiàn)。
優(yōu)點
客戶端不需要在負責(zé)對象的創(chuàng)建,從而明確了各個類的職責(zé),如果有新的對象增加,只需要增加一個具體的類和具體的工廠類即可,不影響已有的代碼,后期維護容易,增強了系統(tǒ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 {// 實現(xiàn)接口 public Animal createAnimal() { return new Dog(); }} class CatFactory implements Factory {// 實現(xiàn)接口 public Animal createAnimal() { return new Cat(); }}感謝閱讀,希望能幫助到大家,謝謝大家對本站的支持!
新聞熱點
疑難解答
圖片精選