Java反射研究(3)

來源:互聯網
上載者:User
文章目錄
  • 1.最簡單的工廠設計模式
  • 2.通過反射實現
  • 3.增加靈活性:設定檔
十一、工廠設計模式1.最簡單的工廠設計模式

情境:有一個Fruit介面,Apple類和Orange類都實現了Fruit介面,Factory用來生產水果;

import java.io.*;import java.util.*;interface Fruit{public void eat();}class Apple implements Fruit{public void eat(){System.out.println("吃蘋果");}}class Orange implements Fruit{public void eat(){System.out.println("吃橘子");}}class Factory{public static Fruit getInstance(String name)throws Exception{Fruit f = null;if("apple".equals(name)){f = new Apple();}else if("orange".equals(name)){f = new Orange();}if(f!=null){return f;}else return null;}}public class FactoryDemo01{public static void main(String args[])throws Exception{Fruit f = Factory.getInstance("apple");f.eat();}}

2.通過反射實現

上面的例子有一個壞處,就是在Factory的getInstance代碼會隨著水果數量增加而增加,比如如果增加了一個banana類,則需要添加

if(name.equals("banana")){...}

這樣非常不方便,因此反射就是一個很好的解決方案:

import java.io.*;import java.util.*;interface Fruit{public void eat();}class Apple implements Fruit{public void eat(){System.out.println("吃蘋果");}}class Orange implements Fruit{public void eat(){System.out.println("吃橘子");}}class Factory{public static Fruit getInstance(String name)throws Exception{Fruit f = nullFruit f = (Fruit)Class.forName(name).newInstance();if(f!=null){return f;}else return null;}}public class FactoryDemo01{public static void main(String args[])throws Exception{Fruit f = Factory.getInstance("Apple");f.eat();}}

3.增加靈活性:設定檔

但是還有一個缺點,就是如果Apple類等有包名,則如果要訪問此類,必須添加包名+類名稱才可以。比如Apple類的最上方:package org;則必須通過org.Apple才可以訪問Apple類。因此通過Properties檔案可以解決這個問題;

import java.io.*;import java.util.*;interface Fruit{public void eat();}class Apple implements Fruit{public void eat(){System.out.println("吃蘋果");}}class Orange implements Fruit{public void eat(){System.out.println("吃橘子");}}class Factory{public static Fruit getInstance(String name)throws Exception{Fruit f = nullFruit f = (Fruit)Class.forName(name).newInstance();if(f!=null){return f;}else return null;}        private Factory(){}}public class FactoryDemo01{public static void main(String args[])throws Exception{Properties p = new Properties();p.load(new FileInputStream("1.properties"));String str = p.getProperty("apple");Fruit f = Factory.getInstance(str);f.eat();}}

1.properties代碼:

apple=Appleorange=Orange

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在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.