posts - 51, comments - 17, trackbacks - 0, articles - 9
            BlogJava :: 首頁(yè) :: 新隨筆 :: 聯(lián)系 :: 聚合  :: 管理

          java模式之享元模式

          Posted on 2007-03-23 19:45 chenweicai 閱讀(293) 評(píng)論(0)  編輯  收藏

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

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

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

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

          如何使用?

          我們先從Flyweight抽象接口開(kāi)始:

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

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

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

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

          }

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

          public class UnsharedConcreteFlyweight implements Flyweight {

            public void operation( ExtrinsicState state ) { }

          }

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

          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)用上看,好象是個(gè)純粹的Factory使用,但奧妙就在于Factory的內(nèi)部設(shè)計(jì)上.

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

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

          其中,歌唱者姓名有可能重復(fù),也就是說(shuō),可能有同一個(gè)演唱者的多個(gè)不同時(shí)期 不同曲目的CD.我們將"歌唱者姓名"作為可共享的ConcreteFlyweight.其他兩個(gè)字段作為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ù)的小類(lèi),因?yàn)槠渲谐煞种挥腥齻€(gè)字段,而且有重復(fù)的(歌唱者姓名).

          CD就是類(lèi)似上面接口 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,專(zhuān)門(mén)用來(lái)制造上面的可共享的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時(shí),Flyweight模式將節(jié)省更多空間,共享的flyweight越多,空間節(jié)省也就越大.


          給個(gè)例子,coffee商店

          package FlyWeight.coffeeshop;

          public class Table {
          ?
          ?private int number;

          ?public int getNumber() {
          ??return number;
          ?}

          ?public void setNumber(int number) {
          ??this.number = number;
          ?}

          ?public Table(int number) {
          ??super();
          ??// TODO Auto-generated constructor stub
          ??this.number = number;
          ?}

          }


          package FlyWeight.coffeeshop;

          public abstract class Order {
          ?
          ?public abstract void serve(Table table);
          ?
          ?public abstract String getFlavor();

          }


          package FlyWeight.coffeeshop;

          public class Flavor extends Order {

          ?private String flavor;

          ?public Flavor(String flavor) {
          ??super();
          ??// TODO Auto-generated constructor stub
          ??this.flavor = flavor;
          ?}

          ?public String getFlavor() {
          ??return flavor;
          ?}

          ?public void setFlavor(String flavor) {
          ??this.flavor = flavor;
          ?}

          ?public void serve(Table table) {
          ??System.out.println("Serving table " + table.getNumber() + " with flavor " + flavor );
          ?}?
          }

          package FlyWeight.coffeeshop;

          public class FlavorFactory {

          ?private Order[] flavors = new Flavor[10];
          ?private int ordersMade = 0;//已經(jīng)處理好的訂單數(shù)
          ?private int totalFlavors = 0;//已購(gòu)買(mǎi)的coffee風(fēng)味種類(lèi)數(shù)
          ?
          ?public Order getOrder(String flavorToGet){
          ??if(ordersMade > 0){
          ???for(int i=0; i<ordersMade; i++){
          ????if(flavorToGet.equalsIgnoreCase(flavors[i].getFlavor()))
          ?????return flavors[i];
          ???}
          ??}
          ??flavors[ordersMade] = new Flavor(flavorToGet);
          ??totalFlavors++;
          ??return flavors[ordersMade++];
          ?}
          ?
          ?public int getTotalFlavorsMade(){
          ??return totalFlavors;
          ?}
          }


          package FlyWeight.coffeeshop;

          public class Client {
          ?
          ?private static Order[] flavors = new Flavor[100];
          ?
          ?private static int ordersMade = 0;
          ?private static FlavorFactory flavorFactory;
          ?
          ?private static void takeOrders(String aFlavor){
          ??flavors[ordersMade++] = flavorFactory.getOrder(aFlavor);
          ?}
          ?
          ?public static void main(String[] args){
          ??flavorFactory = new FlavorFactory();
          ??
          ???? takeOrders("Black Coffee");
          ???? takeOrders("Capucino");
          ???? takeOrders("Espresso");
          ???? takeOrders("Espresso");
          ???? takeOrders("Capucino");
          ???? takeOrders("Capucino");
          ???? takeOrders("Black Coffee");
          ???? takeOrders("Espresso");
          ???? takeOrders("Capucino");
          ???? takeOrders("Black Coffee");
          ???? takeOrders("Espresso");
          ????
          ???? for(int i=0; i<ordersMade; i++){
          ???? ?flavors[i].serve(new Table(i));
          ???? }
          ????
          ???? System.out.println("\nTotal Flavor objrcts made: " +
          ???? ??flavorFactory.getTotalFlavorsMade());
          ?}
          ?
          }

          //-------------------------------------------------------------------

          運(yùn)行結(jié)果:

          Serving table 0 with flavor Black Coffee
          Serving table 1 with flavor Capucino
          Serving table 2 with flavor Espresso
          Serving table 3 with flavor Espresso
          Serving table 4 with flavor Capucino
          Serving table 5 with flavor Capucino
          Serving table 6 with flavor Black Coffee
          Serving table 7 with flavor Espresso
          Serving table 8 with flavor Capucino
          Serving table 9 with flavor Black Coffee
          Serving table 10 with flavor Espresso

          Total Flavor objrcts made: 3


          只有注冊(cè)用戶(hù)登錄后才能發(fā)表評(píng)論。


          網(wǎng)站導(dǎo)航:
           
          主站蜘蛛池模板: 淮北市| 汉川市| 楚雄市| 景洪市| 北安市| 盖州市| 丰城市| 夏津县| 长汀县| 肥城市| 开化县| 安国市| 广汉市| 旌德县| 塔河县| 紫阳县| 康定县| 南城县| 寻甸| 砀山县| 塔城市| 闽侯县| 沈阳市| 安宁市| 延吉市| 平利县| 广德县| 墨竹工卡县| 铅山县| 旺苍县| 黄陵县| 平顺县| 寿阳县| 定陶县| 康定县| 县级市| 阿克苏市| 昌江| 攀枝花市| 西畴县| 长沙市|