tbwshc

          設(shè)計模式之Flyweight(享元)

          設(shè)計模式之Flyweight(享元)

          Flyweight定義:
          避免大量擁有相同內(nèi)容的小類的開銷(如耗費內(nèi)存),使大家共享一個類(元類).

          為什么使用?
          面向?qū)ο笳Z言的原則就是一切都是對象,但是如果真正使用起來,有時對象數(shù)可能顯得很龐大,比如,字處理軟件,如果以每個文字都作為一個對象,幾千個字,對象數(shù)就是幾千,無疑耗費內(nèi)存,那么我們還是要"求同存異",找出這些對象群的共同點,設(shè)計一個元類,封裝可以被共享的類,另外,還有一些特性是取決于應(yīng)用(context),是不可共享的,這也Flyweight中兩個重要概念內(nèi)部狀態(tài)intrinsic和外部狀態(tài)extrinsic之分.

          說白點,就是先捏一個的原始模型,然后隨著不同場合和環(huán)境,再產(chǎn)生各具特征的具體模型,很顯然,在這里需要產(chǎn)生不同的新對象,所以Flyweight模式中常出現(xiàn)Factory模式.Flyweight的內(nèi)部狀態(tài)是用來共享的,Flyweight factory負(fù)責(zé)維護(hù)一個Flyweight pool(模式池)來存放內(nèi)部狀態(tài)的對象.

          Flyweight模式是一個提高程序效率和性能的模式,會大大加快程序的運行速度.應(yīng)用場合很多:比如你要從一個數(shù)據(jù)庫中讀取一系列字符串,這些字符串中有許多是重復(fù)的,那么我們可以將這些字符串儲存在Flyweight池(pool)中.

          如何使用?

          我們先從Flyweight抽象接口開始:

          public interface Flyweightb
          {
            public void operation( ExtrinsicState state );
          }

          //用于本模式的抽象數(shù)據(jù)類型(自行設(shè)計)
          public interface ExtrinsicState { }

          下面是接口的具體實現(xiàn)(ConcreteFlyweight) ,并為內(nèi)部狀態(tài)增加內(nèi)存空間, ConcreteFlyweight必須是可共享的,它保存的任何狀態(tài)都必須是內(nèi)部(intrinsic),也就是說,ConcreteFlyweight必須和它的應(yīng)用環(huán)境場合無關(guān).

          public class ConcreteFlyweight implements Flyweight {
            private IntrinsicState state;
            
            public void operation( ExtrinsicState state )
            {
                //具體操作
            }

          }

          當(dāng)然,并不是所有的Flyweight具體實現(xiàn)子類都需要被共享的,所以還有另外一種不共享的ConcreteFlyweight:

          public class UnsharedConcreteFlyweight implements Flyweight {

            public void operation( ExtrinsicState state ) { }

          }

          Flyweight factory負(fù)責(zé)維護(hù)一個Flyweight池(存放內(nèi)部狀態(tài)),當(dāng)客戶端請求一個共享Flyweight時,這個factory首先搜索池中是否已經(jīng)有可適用的,如果有,factory只是簡單返回送出這個對象,否則,創(chuàng)建一個新的對象,加入到池中,再返回送出這個對象.池

          public class FlyweightFactory {
            //Flyweight pool
            private Hashtable flyweights = new Hashtable();

            public Flyweight getFlyweight( Object key ) {

              Flyweight flyweight = (Flyweight) flyweights.get(key);

              if( flyweight == null ) {
                //產(chǎn)生新的ConcreteFlyweight
                flyweight = new ConcreteFlyweight();
                flyweights.put( key, flyweight );
              }

              return flyweight;
            }
          }

          至此,Flyweight模式的基本框架已經(jīng)就緒,我們看看如何調(diào)用:

          FlyweightFactory factory = new FlyweightFactory();
          Flyweight fly1 = factory.getFlyweight( "Fred" );
          Flyweight fly2 = factory.getFlyweight( "Wilma" );
          ......

          從調(diào)用上看,好象是個純粹的Factory使用,但奧妙就在于Factory的內(nèi)部設(shè)計上.

          Flyweight模式在XML等數(shù)據(jù)源中應(yīng)用
          我們上面已經(jīng)提到,當(dāng)大量從數(shù)據(jù)源中讀取字符串,其中肯定有重復(fù)的,那么我們使用Flyweight模式可以提高效率,以唱片CD為例,在一個XML文件中,存放了多個CD的資料.

          每個CD有三個字段:
          1.出片日期(year)
          2.歌唱者姓名等信息(artist)
          3.唱片曲目 (title)

          其中,歌唱者姓名有可能重復(fù),也就是說,可能有同一個演唱者的多個不同時期 不同曲目的CD.我們將"歌唱者姓名"作為可共享的ConcreteFlyweight.其他兩個字段作為UnsharedConcreteFlyweight.

          首先看看數(shù)據(jù)源XML文件的內(nèi)容:


          <?xml version="1.0"?>
          <collection>

          <cd>
          <title>Another Green World</title>
          <year>1978</year>
          <artist>Eno, Brian</artist>
          </cd>

          <cd>
          <title>Greatest Hits</title>
          <year>1950</year>
          <artist>Holiday, Billie</artist>
          </cd>

          <cd>
          <title>Taking Tiger Mountain (by strategy)</title>
          <year>1977</year>
          <artist>Eno, Brian</artist>
          </cd>

          .......

          </collection>


          雖然上面舉例CD只有3張,CD可看成是大量重復(fù)的小類,因為其中成分只有三個字段,而且有重復(fù)的(歌唱者姓名).

          CD就是類似上面接口 Flyweight:


          public class CD {

            private String title;
            private int year;
            private Artist artist;

            public String getTitle() {  return title; }
            public int getYear() {    return year;  }
            public Artist getArtist() {    return artist;  }

            public void setTitle(String t){    title = t;}
            public void setYear(int y){year = y;}
            public void setArtist(Artist a){artist = a;}

          }

          "歌唱者姓名"作為可共享的ConcreteFlyweight:

          public class Artist {

            //內(nèi)部狀態(tài)
            private String name;

            // note that Artist is immutable.
            String getName(){return name;}

            Artist(String n){
              name = n;
            }

          }

          再看看Flyweight factory,專門用來制造上面的可共享的ConcreteFlyweight:Artist

          public class ArtistFactory {

            Hashtable pool = new Hashtable();

            Artist getArtist(String key){

              Artist result;
              result = (Artist)pool.get(key);
              ////產(chǎn)生新的Artist
              if(result == null) {
                result = new Artist(key);
                pool.put(key,result);
                
              }
              return result;
            }

          }

          當(dāng)你有幾千張甚至更多CD時,Flyweight模式將節(jié)省更多空間,共享的flyweight越多,空間節(jié)省也就越大.

          posted on 2012-07-16 13:25 chen11-1 閱讀(869) 評論(0)  編輯  收藏


          只有注冊用戶登錄后才能發(fā)表評論。


          網(wǎng)站導(dǎo)航:
           
          主站蜘蛛池模板: 安庆市| 仁寿县| 灌南县| 西安市| 板桥市| 华蓥市| 扶沟县| 松潘县| 嘉兴市| 三亚市| 文安县| 休宁县| 芦山县| 柳州市| 城固县| 泸水县| 玉门市| 潮州市| 长寿区| 绍兴县| 南涧| 临澧县| 定兴县| 阿图什市| 金昌市| 如皋市| 红桥区| 安陆市| 梅河口市| 堆龙德庆县| 旬邑县| 闸北区| 威信县| 行唐县| 泸溪县| 垣曲县| 潞城市| 五寨县| 三河市| 平谷区| 东城区|