NOTE
Factory Method
Factory methods delegate concrete-product creation to corresponding factories so callers depend on a creation interface. These notes compare them with simple factories through code.
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 defers object creation until it is needed in the subclass.
1. UML
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()
}
Drag to pan, scroll to zoom, and click a node to expand or collapse it. Large maps start with deeper levels collapsed; click nodes to expand them.
Discussion
Sign in with GitHub to comment. Discussions are stored as GitHub Issues.View on GitHub