Java Reference
In-Depth Information
Clients of the Chemical class can pass in the mass of a batch of a given chemical to
determine its molality. The code for getMoles() in the Chemical class accepts a mass
parameter:
public double getMoles(double grams)
{
return grams / atomicWeight;
}
The Substance version of getMoles() applies the mass of the chemical batch it
represents:
public double getMoles()
{
return chemical.getMoles(grams);
}
SOLUTION 13.4
To prevent developers from instantiating the Chemical class themselves, you can place
Chemical and ChemicalFactory in the same package and give the Chemical class's
constructor package visibility. Note that if you make its constructor private, even
ChemicalFactory won't be able to create Chemical objects.
SOLUTION 13.5
Controlling the instantiation of Chemical objects by applying an inner class is a more
complex but more thorough approach. The resulting code will look something like this:
package com.oozinoz.chemical;
import java.util.*;
public class ChemicalFactory
{
private static Map chemicals = new HashMap();
static
{
chemicals.put(
"carbon",
new ChemicalImpl("Carbon", "C", 12));
//...
}
private static class ChemicalImpl implements Chemical
{
private String name;
private String symbol;
private double atomicWeight;
//
private ChemicalImpl(
String name, String symbol, double atomicWeight)
{
this.name = name;
this.symbol = symbol;
Search WWH ::




Custom Search