Flyweight Pattern Reuse without multiple instances to be memory friendly
This page describes the following ・ Basic configuration of Flyweight ·Implementation
class | Explanation |
---|---|
factory.class | sam.Do not duplicate instances of class |
sam.class | Target class for which user instantiates |
user(Main.class) | factory.sam via class.Create a class instance |
Basic structure of factory.class and sam.class
factory.class
class factory{
Map map;
sam getSam(){}
}
In factory, the generated sam () instance is held in Map Manage to avoid duplication
sam.class
class sam{
String s;
sam(){}
}
sam () registers String s in the constructor
Implement the basic structure below
factory.class
class factory{
Map map = new HashMap(); // sam()Store the instance
sam getSam(String key){
sam s = (sam) map.get(key); //Get an instance from map
if(s != null){return s;} //If there is an instance on the map, pass it to user
sam sm= new sam(key); //If there is no instance in map, create an instance
map.put(key,sm); //After creating a new instance, register it in map
return sm; //Publish an instance to user
}
}
sam.class
class sam{
String s;
sam(String s){}
}
There is a problem with the above code. The factory has a Map and manages the sam () instance. When the factory itself is made into multiple interfaces, different maps will be created by that number.
If that happens, you will not be able to manage the sam () instance properly. So let factory.class be a singleton (It is not possible to prevent the duplication of the map by itself, but as a temporary process)
Also implement a print () method that prints the Map contents for further verification
factory.class
class factory{Map map = new HashMap();
private static final factory fac = new factory();
private factory(){}
static factory getInstance(){
return fac;
}
sam getSam(String key){
sam s = (sam) map.get(key);
if( s != null){return s;}
sam sm = new sam(key);
map.put(key,sm);
return sm;
}
void print(){
Iterator it = map.keySet().iterator();
while(it.hasNext()){
sam s = (sam) map.get(it.next());
System.out.println(s+":"+s.get());
}
}
}
sam.class
class sam{
private String s;
sam(String s){this.s=s;}
String get(){return this.s;}
}
user(Main.class)
public static void main(String[] args){
factory f = factory.getInstance();
f.getSam("a");
f.getSam("b");
f.getSam("c");
f.getSam("a");
f.print();
}}
Recommended Posts