ITPub博客

首页 > Linux操作系统 > Linux操作系统 > Java与模式之享元(Flyweigt)模式

Java与模式之享元(Flyweigt)模式

原创 Linux操作系统 作者:liuzhili3608 时间:2008-04-05 14:19:30 0 删除 编辑

    享元模式是对象的结构模式[GOF95]。享元模式以共享的方式高效的支持大量的细粒度对象。

//单纯享元模式的结构
//抽象享元角色
abstract public class Flyweight
{
    abstract public void operation(String state);
}
//具体享元(ConcreteFlyweight)角色
public class ConcreteFlyweight extends Flyweight
{
    private Character intrinsicState = null;

 public ConcreteFlyweight(Character state)
 {
  this.intrinsicState = state;
 }
 
 public void operation(String state)
 {
  System.out.print( "\nIntrinsic State = " + intrinsicState +
            ", Extrinsic State = " + state);
 }
}
//享元工厂(FlyweightFactory)角色
import java.util.Map;
import java.util.HashMap;
import java.util.Iterator;

public class FlyweightFactory
{
    private HashMap flies = new HashMap();
    /**
     * @link aggregation
     * @directed
     * @clientRole Flyweights
     */
    private Flyweight lnkFlyweight;

 public FlyweightFactory(){}
 
 public synchronized Flyweight factory(Character state)
 {
  if ( flies.containsKey( state ) )
        {
            return (Flyweight) flies.get( state );
        }
        else
        {
   Flyweight fly = new ConcreteFlyweight( state );
            flies.put( state , fly);
            return fly;
        }
 }
 
 public void checkFlyweight()
 {
  Flyweight fly ;
        int i = 0;

        System.out.println("\n==========checkFlyweight()=============");
  for ( Iterator it = flies.entrySet().iterator() ; it.hasNext() ;  )
        {
   Map.Entry e = (Map.Entry) it.next();
            System.out.println("Item " + (++i) + " : " + e.getKey());
        }
        System.out.println("==========checkFlyweight()=============");
 }

}
//客户端(Client)角色
public class Client
{
    private static FlyweightFactory factory;

    static public void main(String[] args)
 {
  factory = new FlyweightFactory();

  Flyweight fly = factory.factory(new Character('a'));
  fly.operation("First Call");
  
  fly = factory.factory(new Character('b'));
  fly.operation("Second Call");
  
  fly = factory.factory(new Character('a'));
  fly.operation("Third Call");
  
  // intrinsic Flyweight
  factory.checkFlyweight();
 }
}

//复合享元模式的结构
//抽象享元角色
abstract public class Flyweight
{
    abstract public void operation(String state);
}
//具体享元(ConcreteFlyweight)角色
public class ConcreteFlyweight extends Flyweight
{
    private Character intrinsicState = null;

 public ConcreteFlyweight(Character state)
 {
  this.intrinsicState = state;
 }
 
 public void operation(String state)
 {
  System.out.print( "\nInternal State = " +
            intrinsicState + " Extrinsic State = " + state );
 }
}
//复合享元(UnsharableFlyweight)角色
import java.util.Map;
import java.util.HashMap;
import java.util.Iterator;

public class ConcreteCompositeFlyweight extends Flyweight
{
    private HashMap flies = new HashMap(10);

    /**
     * @link aggregation
     * @directed
     * @clientRole Composite
     */
    private Flyweight flyweight;

 public ConcreteCompositeFlyweight()
 {
 }
 
 public void add(Character key, Flyweight fly)
 {
  flies.put(key, fly);
 }
 
 public void operation(String extrinsicState)
 {
        Flyweight fly =  null;

  for ( Iterator it = flies.entrySet().iterator() ; it.hasNext() ;  )
        {
   Map.Entry e = (Map.Entry) it.next();
            fly = (Flyweight) e.getValue();

            fly.operation(extrinsicState);
        }
 }
}
//享元工厂(FlyweightFactory)角色
import java.util.Map;
import java.util.HashMap;
import java.util.Iterator;

public class FlyweightFactory
{
    private HashMap flies = new HashMap();
    /**
     * @link aggregation
     * @directed
     * @clientRole Flyweights
     */
    private Flyweight lnkFlyweight;

 public FlyweightFactory(){}

 public Flyweight factory(String compositeState)
 {
  ConcreteCompositeFlyweight compositeFly = new ConcreteCompositeFlyweight();
  
  int length = compositeState.length();
        Character state = null;

  for(int i = 0; i < length; i++)
  {
   state = new Character(compositeState.charAt(i) );
            System.out.println("factory(" + state + ")");
   compositeFly.add( state, this.factory( state) );
  }
  return compositeFly;
    }

 public Flyweight factory(Character state)
 {
  if ( flies.containsKey( state ) )
        {
            return (Flyweight) flies.get( state );
        }
        else
        {
   Flyweight fly = new ConcreteFlyweight( state );
            flies.put( state , fly);
            return fly;
        }
 }
 
 public void checkFlyweight()
 {
  Flyweight fly ;
        int i = 0 ;

        System.out.println("\n==========checkFlyweight()=============");
  for ( Iterator it = flies.entrySet().iterator() ; it.hasNext() ;  )
        {
   Map.Entry e = (Map.Entry) it.next();
            System.out.println( "Item " + (++i) + " : " + e.getKey());
        }
        System.out.println("\n==========checkFlyweight()=============");
 }

}
//客户端(Client)角色
public class Client
{
    private static FlyweightFactory factory;

    public static void main(String[] args)
 {
  factory = new FlyweightFactory();

  Flyweight fly;
/*        fly = factory.factory(new Character('a'));
  fly.operation();
  
  fly = factory.factory(new Character('b'));
  fly.operation();
  
  fly = factory.factory(new Character('a'));
  fly.operation();
*/
        fly = factory.factory("abc");
        fly.operation("Composite Call");
  
// intrinsic Flyweight
  factory.checkFlyweight();
 }
}

一个咖啡摊的例子

package com.javapatterns.flyweight.coffeestall;

public abstract class Order

    public abstract void serve();

    public abstract String getFlavor();

}

package com.javapatterns.flyweight.coffeestall;

public class Flavor extends Order

 private String flavor;
 
 public Flavor(String flavor)
 {
     this.flavor = flavor;
 }
 
 public String getFlavor()
 {
     return this.flavor;
 }
 
 public void serve()
 {
     System.out.println("Serving flavor " + flavor );
 }
}

package com.javapatterns.flyweight.coffeestall;

public class FlavorFactory

 /**
  * @label Flyweight
  * @supplierCardinality 0..*
  * @link aggregation
  */
 private Order[] flavors = new Flavor[10];
 private int rdersMade = 0;
    private int totalFlavors = 0 ;
 
 public Order getOrder(String flavorToGet)
 {
     if (ordersMade > 0)
     {
         for (int i = 0; i < ordersMade; i++)
         {
             if (flavorToGet.equals((flavors[i]).getFlavor()))
             {
                 return flavors[i];
             }
         }
     }
     flavors[ordersMade] = new Flavor(flavorToGet);
        totalFlavors++;
     return flavors[ordersMade++];
 }
 
 public int getTotalFlavorsMade()
 {
      return totalFlavors;
 }
}

package com.javapatterns.flyweight.coffeestall;

public class Client
{
 //the flavors ordered


    /**
     * @supplierCardinality 0..*
     */
 private static Order[] flavors = new Flavor[100];

 private static int rdersMade = 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();
     }

     System.out.println("\nTotal teaFlavor objects made: " +
            flavorFactory.getTotalFlavorsMade());
 }
}

咖啡屋的例子

package com.javapatterns.flyweight.coffeeshop;

public abstract class Order

    public abstract void serve(Table table);

    public abstract String getFlavor();

    /** @link dependency */
    /*#Table lnkTable;*/
}

package com.javapatterns.flyweight.coffeeshop;

public class Flavor extends Order

 private String flavor;
 
 public Flavor(String flavor)
 {
     this.flavor = flavor;
 }
 
 public String getFlavor()
 {
     return this.flavor;
 }
 
 public void serve(Table table)
 {
     System.out.println("Serving table " + table.getNumber() + " with flavor " + flavor );
 }
}

package com.javapatterns.flyweight.coffeeshop;

public class FlavorFactory

 /**
  * @label Flyweight
  * @link aggregation
  */
 private Order[] flavors = new Flavor[10];
 private int rdersMade = 0;
    private int totalFlavors = 0 ;
 
 public Order getOrder(String flavorToGet)
 {
     if (ordersMade > 0)
     {
         for (int i = 0; i < ordersMade; i++)
         {
             if (flavorToGet.equals((flavors[i]).getFlavor()))
             {
                 return flavors[i];
             }
         }
     }
     flavors[ordersMade] = new Flavor(flavorToGet);
        totalFlavors++;
     return flavors[ordersMade++];
 }
 
 public int getTotalFlavorsMade()
 {
      return totalFlavors;
 }
}

package com.javapatterns.flyweight.coffeeshop;

public class Table
{
    private int number;

    public Table(int number)
    {
        this.number = number;
    }

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

    public int getNumber()
    {
        return number;
    }

}

package com.javapatterns.flyweight.coffeeshop;

public class Client
{
 //the flavors ordered


    /**
     * @label Creates
     */
 private static Order[] flavors = new Flavor[100];

 private static int rdersMade = 0;
 private static FlavorFactory flavorFactory;

    /** @link dependency */
    /*#Table lnkTable;*/
 
 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 teaFlavor objects made: " +
            flavorFactory.getTotalFlavorsMade());
 }
}

来自 “ ITPUB博客 ” ,链接:http://blog.itpub.net/12993749/viewspace-228953/,如需转载,请注明出处,否则将追究法律责任。

请登录后发表评论 登录
全部评论

注册时间:2008-03-25

  • 博文量
    34
  • 访问量
    57402