I wanted to verify is this a good example of a flyweight design pattern:
package com.flyweight;
public interface Chemical {
String getName();
String getSymbol();
Double getAtomicWeight();
}
package com.flyweight;
import java.util.HashMap;
import java.util.Map;
public class ChemicalFactory {
private static Map chemicals = new HashMap();
private static ChemicalFactory factory = new ChemicalFactory();
class ChemicalImpl implements Chemical{
private String name;
private String symbol;
private Double atomicWeight;
public ChemicalImpl(String name, String symbol, Double atomicWeight){
this.name = name;
this.symbol = symbol;
this.atomicWeight = atomicWeight;
}
public String getName() {
return name;
}
public String getSymbol() {
return symbol;
}
public Double getAtomicWeight() {
return atomicWeight;
}
}
static{
chemicals.put("Sulfer", factory.new ChemicalImpl("Sulfer","S",32.0));
chemicals.put("Carbon", factory.new ChemicalImpl("Carbon","C",12.0));
chemicals.put("Saltpeter", factory.new ChemicalImpl("Saltpeter","KN03",101.0));
}
public static Chemical getChemical(String name){
return (Chemical) chemicals.get(name);
}
}
package com.flyweight;
public class Substance {
private Double grams;
private Chemical chemical;
public Substance(Double grams,Chemical chemical){
this.grams = grams;
this.chemical = chemical;
}
public String getName() {
return chemical.getName();
}
public String getSymbol() {
return chemical.getSymbol();
}
public Double getAtomicWeight() {
return chemical.getAtomicWeight();
}
public Double getGrams() {
return grams;
}
public String toString(){
return getName() + " (" + getSymbol() + ") [" + getAtomicWeight() + "]";
}
}
package com.flyweight;
public class Test {
public static void main(String[] args){
Chemical c = ChemicalFactory.getChemical("Sulfer");
Substance s = new Substance(50.0,c);
System.out.println(s);
}
}
Your help is kindly appreciated.
Thank You.