自學ioc

來源:互聯網
上載者:User

標籤:style   blog   http   java   color   使用   

渣渣,叔被面過這麼多次,怎麼可能不會扯ioc,不過如果做一個,或許比扯更有意思,以下為我自學ioc的路線
  
一:我先整個ioc:我記得ioc最著名的容器是spring,形式上是用設定檔進行類的建立...大致路線為xml->map->bean,知道這些我就可以先走一個
1.bean:ioc容器存的是bean,我最好現有一個bean,屬性最好少一點,這樣不至於太尷尬

package bean;public class Student {    private String name;    public String getName() {        return name;    }    public void setName(String name) {        this.name = name;    }    }
View Code  

2.xml:我知道xml是什麼,但是...
nothing,度個娘,大致是這麼個樣子,這樣的話我的ioc容器就可以長成這個樣子

<?xml version="1.0" encoding="UTF-8"?><ioc>    <bean id="english" class="bean.Student">        <name>李雷</name>    </bean>            <bean id="chinese" class="bean.Student">        <name>韓梅梅</name>    </bean></ioc>
View Code

3.xml->map,將設定檔讀取到map/記憶體中
1.我需要瞭解路徑的尋找,我有點忘了,我得參考下擷取檔案的方式
2.對xml的操作,我知道有個dom4j,但是我沒用過,不過我有api

package ioc;import java.io.File;import java.util.HashMap;import java.util.Iterator;import java.util.List;import java.util.Map;import org.apache.commons.beanutils.BeanUtils;import org.dom4j.Document;import org.dom4j.Element;import org.dom4j.io.SAXReader;@SuppressWarnings({"unchecked","rawtypes"})public class Init {        private static Map<String, Object> ioc = new HashMap<String, Object>();    public static Object getBean(String key){        return ioc.get(key);    }        public Init(){        try {            readXml("src/ioc.xml");        } catch (Exception e) {            e.printStackTrace();        }    }        public static void readXml(String file) throws Exception {        Document doc = load(file);        Element root = doc.getRootElement();        for (Iterator iterator = root.elementIterator(); iterator.hasNext();) {            Element e = (Element) iterator.next();            String _id = e.attributeValue("id");            String _class = e.attributeValue("class");                        List<Element> list = e.elements();            Map<String, String> map = new HashMap<String, String>();            for (Element _e : list) {                map.put(_e.getName(), _e.getText());            }                   Object obj=Class.forName(_class).newInstance();            BeanUtils.populate(obj, map);            ioc.put(_id, obj);        }    }    public static Document load(String filename) {        Document document = null;        try {            document = new SAXReader().read(new File(filename));        } catch (Exception ex) {            ex.printStackTrace();        }        return document;    }}
View Code

4.test

    public static void main(String[] args) {        new Init();        Student english = (Student) Init.getBean("english");        Student chinese = (Student) Init.getBean("chinese");        System.out.println("我是英語課代表:"+english.getName());        System.out.println("我是語文課代表:"+chinese.getName());    }

思考:他/ioc突然給了我一種變數的感覺,如果沒有變數,就算是局部變數,那也會照成混亂,噁心,難受的情況(他們說這叫耦合),而變數解決了這個方法中的這個情況,ioc難道不是整個程式中專門提供變數類(變類)的一個方式?那樣的話如果需要寫ioc作用或者意義的話,就可以抄變數的(作用和意義的文章)了
總結:ioc就是為整個程式提供變數類

二:度娘ioc的理解:就好像看到新大陸一樣,我迫不及待的度了個娘

度娘解釋,維基解釋:這些解釋感覺就像神仙打架,也就湊個熱鬧,捧個人場,噹噹炮灰...不過注意到設計模式,和依賴注入的實現方式到讓我想起了GOF第一種模式

女朋友解釋,齒輪解釋:非常形象的解釋

三:策略模式與ioc容器的使用:記得我剛才想到的GOF第一種模式把,果斷撈出來用用-->這裡用spring,我的ioc不支援ref--!

將策略模式最後測試案例改一下,其中xml為:

<bean id="FlyNoWay" class="gof.fly.FlyNoWay"></bean><bean id="FlyRocketPowered" class="gof.fly.FlyRocketPowered"></bean><bean id="FlyWithWings" class="gof.fly.FlyWithWings"></bean><bean id="MuteQuack" class="gof.quack.MuteQuack"></bean><bean id="Quack" class="gof.quack.Quack"></bean><bean id="Squeak" class="gof.quack.Squeak"></bean>         <bean id="綠毛鴨" class="gof.Duck">        <property name="name" value="綠毛鴨"></property>        <property name="flyBehavior" ref="FlyWithWings"></property>        <property name="quackBehavior" ref="Quack"></property>    </bean>            <bean id="紅頭鴨" class="gof.Duck">        <property name="name" value="紅頭內褲外穿鴨"></property>        <property name="flyBehavior" ref="FlyRocketPowered"></property>        <property name="quackBehavior" ref="Squeak"></property>    </bean>                <bean id="模型鴨" class="gof.Duck">        <property name="name" value="模型鴨"></property>        <property name="flyBehavior" ref="FlyNoWay"></property>        <property name="quackBehavior" ref="MuteQuack"></property>    </bean>
View Code

測試為:

            ClassPathXmlApplicationContext ctx =new  ClassPathXmlApplicationContext("applicationContext.xml");            ((Duck) ctx .getBean("綠毛鴨")).display();            ((Duck) ctx .getBean("紅頭鴨")).display();            ((Duck) ctx .getBean("模型鴨")).display();
View Code

至於結果,你懂得:

看,鴨子綠毛鴨正在用翅膀飛行嘎嘎叫看,鴨子紅頭內褲外穿鴨坐火箭飛吱吱叫看,鴨子模型鴨不會飛不會叫
View Code

總結:如果ioc是一種模式,那一定是策略模式+原廠模式,也可以說是具有初始化功能(可配置)的原廠模式,當然,如果你要面試千萬不要學我,說多了都是鼻涕...
四:我需要個能在web上跑的ioc:我瞭解到了ioc的模式,可我希望我的ioc也能在web項目下運行,在web下初始化其實程式,不要太簡單

建立一個servlet用來初始化ioc,並指定此ioc在運行時進行載入

  <servlet-mapping>    <servlet-name>InitServlet</servlet-name>    <url-pattern>/servlet/InitServlet</url-pattern>  </servlet-mapping>      <servlet>    <servlet-name>InitServlet</servlet-name>    <servlet-class>ioc.InitServlet</servlet-class>        <load-on-startup>1</load-on-startup>  </servlet>
View Code

思考:web.xml啟動並執行順序有4種,那我豈不是可以有4種啟動方式?
五:我的ioc和spring的區別:既然ioc這麼簡單,為毛要用spring?僅僅是因為不重複造輪子?
xml:我看了下spring的設定檔和我的不一樣,最開始我覺得,沒什麼大不了的,理解不一樣而已,不過看到dtd的時候,秒懂
web.xml:啟動方式果然有好幾種
其他相關功能:看jar包就知道,它提供的功能更多
 
六:照虎畫貓版
spring的提供很多簡易的方式,叔自己不會寫嗎?話說寫完之後感覺沒那麼大,他們源碼裡到底賽的是什麼。。。

七:寫完總結

回見

八:個大ioc使用比較(隨便找點ioc架構以證明我用過很多ioc架構,而spring不愧是spring)
Guice:Google公司開發的輕量級IoC容器
PicoContainer:它利用了Inversion of Control模式和Template Method模式,提供面向組件的開發、運行環境(我喜歡微型的)
Jdon:國產
............
比較後總結:1.類似的架構越來越多,代碼越來越少,速度越來越快,看來得重新理解不要重複製作輪子了。。
               2.深深地感覺到這個充滿惡意的社會....javascript的ioc是個毛意思
八:源碼(spring太牛b了,先看微型的)
姑娘們看源碼理解的時間到了,重在理念,設計/封裝方式,其他略

聯繫我們

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