package funpoly; import funpoly.visitor.IVisitor; /** * * Serves as a factory for manufacturing Polynomial objects. * @author Dung X. Nguyen * @since December 28, 1999 */ public class PolyFactory { /** @SBGen Variable (,Zero Polynomial,,64) */ public final static APolynomial ZeroPoly = new ConstPoly (0); /** * Creates a constant Polynomial. Uses the flyweight pattern for the zero polynomial. * @return a constant Polynomial. */ public static APolynomial MakeConstPoly (int coef) { return 0 == coef? ZeroPoly: new ConstPoly (coef); } /** * Creates a non-constant Polynomial with a given leading coefficient, a given degree, * and a given lower order polynomial. Checks for legal input parameters. * Will ignore zero leading coefficient. * @param coef the leading coefficient. * @param degree the degree, >= 0. * @param lowPoly != null, the lower ordered polynomial with degree < degree. * @return a non-constant Polynomial. * @exception throws IllegalArgumentException if conditions on degree and lowerPoly are violated. */ public static APolynomial MakePoly (int coef, int degree, APolynomial lowerPoly) { if (degree <= 0) { throw new IllegalArgumentException ("Degree must be positive!"); } if (null == lowerPoly) { throw new IllegalArgumentException ("lowerPoly must be non-null!"); } if (0 == coef) { return lowerPoly; } if (degree <= lowerPoly.getDegree()) { throw new IllegalArgumentException ("lowPoly is not a lower order term!"); } return new NonConstPoly (coef, degree, lowerPoly); } /** * A few simple test cases. */ public static void main (String[] args) { APolynomial pc0 = ZeroPoly; APolynomial pc1 = MakeConstPoly (-1); APolynomial p1 = MakePoly (-5, 3, pc0); APolynomial p2 = MakePoly (2, 5, p1); APolynomial p3 = MakePoly (-4, 6, p2); APolynomial p4 = MakePoly (3, 2, pc1); System.out.println ("0 = " + pc0); System.out.println ("-1 = " + pc1); System.out.println ("3x^2 - 1 = " + p4); System.out.println ("-5x^3 + 0 = " + p1); System.out.println ("2x^5 - 5x^3 + 0 = " + p2); System.out.println ("-4x^6 + 2x^5 - 5x^3 + 0 = " + p3); } }