NOTE

Factory Method

The factory-method pattern uses multiple factory classes and delays concrete product creation to subclasses.

Software Architecture & EngineeringCreated Updated 1 min readhistorical

This is a historical learning note and may contain outdated or incomplete understanding.

Compared with a simple factory, there are multiple factory classes. We can pass a concrete factory instance rather than a concrete product to a subclass, and call the factory instance’s product-creation method when needed. This is equivalent to delaying the creation of the instance object to the subclass.

1. UML

PlantUML 图表

2. Java

2.1. Client

public class Client
{
    public static void main(String[] args)
    {
        Car car = new AudiCarFactory().getCar();
        car.run();

        Car car2 = new QQCarFactory().getCar();
        car2.run();
    }
}

2.2. Factory

public interface CarFactory
{
    Car getCar();
}
public class AudiCarFactory implements CarFactory
{
    @Override
    public Car getCar()
    {
        return new AudiCar();
    }
}
public class QQCarFactory implements CarFactory
{
    @Override
    public Car getCar()
    {
        return new QQCar();
    }
}

2.3. Product

public interface Car
{
    void run();
}
public class AudiCar implements Car
{
    @Override
    public void run()
    {
        System.out.println("Audi");
    }
}
public class QQCar implements Car
{
    @Override
    public void run()
    {
        System.out.println("qq car");
    }
}

3. Golang

3.1. Factory

/* Factory interface */
type CarFactory interface {
	CreateCar() Car
}

/* QQ car factory */
type QQCarFactory struct {
}

func (Q QQCarFactory) CreateCar() Car {
	return &QQCar{}
}

/* Audi car factory */
type AodiCarFactory struct {
}

func (a AodiCarFactory) CreateCar() Car {
	return &AodiCar{}
}

3.2. Product

/* Car interface */
type Car interface {
	Run()
}

/* QQ car */
type QQCar struct {
}

func (Q QQCar) Run() {
	fmt.Println("QQ Car")
}

/* Audi car */
type AodiCar struct {
}

func (Q AodiCar) Run() {
	fmt.Println("Aodi Car")
}

3.3. Client

func main() {
	RunCar(&工厂方法.QQCarFactory{})
	RunCar(&工厂方法.AodiCarFactory{})
}

func RunCar(factory 工厂方法.CarFactory)  {
	factory.CreateCar().Run()
}

Discussion

Sign in with GitHub to comment. Discussions are stored as GitHub Issues.View on GitHub