package Flyweight; public abstract class Flyweight ... { public abstract void operation(); }//end abstract class Flyweight |
package Flyweight; public class ConcreteFlyweight extends Flyweight ... { private String string; public ConcreteFlyweight(String str) ... { string = str; }//end ConcreteFlyweight(...) public void operation() ... { System.out.println("Concrete---Flyweight : " + string); }//end operation() }//end class ConcreteFlyweight |
package Flyweight; import java.util.Hashtable; public class FlyweightFactory ... { private Hashtable flyweights = new Hashtable();//----------------------------1 public FlyweightFactory() ...{} public Flyweight getFlyWeight(Object obj) ... { Flyweight flyweight = (Flyweight) flyweights.get(obj);//----------------2 if(flyweight == null) ...{//---------------------------------------------------3 //产生新的ConcreteFlyweight flyweight = new ConcreteFlyweight((String)obj); flyweights.put(obj, flyweight);//--------------------------------------5 } return flyweight;//---------------------------------------------------------6 }//end GetFlyWeight(...) public int getFlyweightSize() ... { return flyweights.size(); } }//end class FlyweightFactory |
package Flyweight; import java.util.Hashtable; public class FlyweightPattern ...{ FlyweightFactory factory = new FlyweightFactory(); Flyweight fly1; Flyweight fly2; Flyweight fly3; Flyweight fly4; Flyweight fly5; Flyweight fly6; /** *//** Creates a new instance of FlyweightPattern */ public FlyweightPattern() ...{ fly1 = factory.getFlyWeight("Google"); fly2 = factory.getFlyWeight("Qutr"); fly3 = factory.getFlyWeight("Google"); fly4 = factory.getFlyWeight("Google"); fly5 = factory.getFlyWeight("Google"); fly6 = factory.getFlyWeight("Google"); }//end FlyweightPattern() public void showFlyweight() ... { fly1.operation(); fly2.operation(); fly3.operation(); fly4.operation(); fly5.operation(); fly6.operation(); int objSize = factory.getFlyweightSize(); System.out.println("objSize = " + objSize); }//end showFlyweight() public static void main(String[] args) ... { System.out.println("The FlyWeight Pattern!"); FlyweightPattern fp = new FlyweightPattern(); fp.showFlyweight(); }//end main(...) }//end class FlyweightPattern |
Concrete---Flyweight : Google Concrete---Flyweight : Qutr Concrete---Flyweight : Google Concrete---Flyweight : Google Concrete---Flyweight : Google Concrete---Flyweight : Google objSize = 2 |
Java设计模式研究之Flyweight模式 src="http://www.ltesting.net/uploads/2007/07/1_200707041222021.jpg" border=0>
|