java 工廠方法詳解及實(shí)例代碼
工廠方法概述
工廠方法模式中抽象工廠類負(fù)責(zé)定義創(chuàng)建對(duì)象的接口,具體對(duì)象的創(chuàng)建工作由繼承抽象工廠的具體類實(shí)現(xiàn)。
優(yōu)點(diǎn)
客戶端不需要在負(fù)責(zé)對(duì)象的創(chuàng)建,從而明確了各個(gè)類的職責(zé),如果有新的對(duì)象增加,只需要增加一個(gè)具體的類和具體的工廠類即可,不影響已有的代碼,后期維護(hù)容易,增強(qiáng)了系統(tǒng)的擴(kuò)展性
缺點(diǎn)
需要額外的編寫代碼,增加子工作量
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 {// 實(shí)現(xiàn)接口 public Animal createAnimal() { return new Dog(); } } class CatFactory implements Factory {// 實(shí)現(xiàn)接口 public Animal createAnimal() { return new Cat(); } }
感謝閱讀,希望能幫助到大家,謝謝大家對(duì)本站的支持!
相關(guān)文章
淺析java并發(fā)中的Synchronized關(guān)鍵詞
這篇文章主要介紹了java并發(fā)中的Synchronized關(guān)鍵詞,本文通過思路代碼給大家介紹的非常詳細(xì),具有一定的參考借鑒價(jià)值,需要的朋友可以參考下2020-02-02Javaweb使用cors完成跨域ajax數(shù)據(jù)交互
本文由跨域、cors的概念開始,進(jìn)而向大家介紹了Javaweb使用cors完成跨域ajax數(shù)據(jù)交互的相關(guān)內(nèi)容,需要的朋友可以了解下。2017-09-09如何使用SpringMVC的消息轉(zhuǎn)換器設(shè)置日期格式
這篇文章主要介紹了如何使用SpringMVC的消息轉(zhuǎn)換器設(shè)置日期格式問題,具有很好的參考價(jià)值,希望對(duì)大家有所幫助,如有錯(cuò)誤或未考慮完全的地方,望不吝賜教2024-07-07