lundi 6 janvier 2020

confused with the definition of factory methods

The GoF definition defines the Factory Method pattern as "lets a class defer instantiation to subclasses". I get the idea, but I also pattern as below:

public class Point
{
    private double x, y;

    protected Point(double x, double y)
    {
        this.x = x;
        this.y = y;
    }
    public static Point NewCartesianPoint(double x, double y)
    {
        return new Point(x, y);
    }
    public static Point NewPolarPoint(double rho, double theta)
    {
        return new Point(rho * Math.Cos(theta), rho * Math.Sin(theta));
    }
}

I know the benefits to use this pattern, but author said NewCartesianPoint and NewPolarPoint are also factory methods.

I'm a little bit confused here, below is my questions:

Q1-there is no even a subclass that derived from Point here, how come they are factory methods?

Q2-If there are also factory methods, then what's the factory here? the Point class?

Aucun commentaire:

Enregistrer un commentaire