Java Reference
In-Depth Information
Figure 13.4. The ChemicalFactory_1 class is a flyweight factory that returns
Chemical objects.
package com.oozinoz.chemical;
import java.util.*;
public class ChemicalFactory_1
{
private static Map chemicals = new HashMap();
static
{
chemicals.put(
"carbon",
new Chemical_1("Carbon", "C", 12));
chemicals.put(
"sulfur",
new Chemical_1("Sulfur", "S", 32));
chemicals.put(
"saltpeter",
new Chemical_1("Saltpeter", "KN03", 101));
//...
}
public static Chemical getChemical(String name)
{
return (Chemical) chemicals.get(name.toLowerCase());
}
}
Having created a factory for chemicals, you now have to take steps to ensure that other
developers use this factory instead of instantiating the Chemical_1 class themselves. A
simple approach is to rely on the visibility of the Chemical_1 class.
Search WWH ::




Custom Search