Intent:Define an interface for creating objects and let subclasses decide which class to instantiate. Factory Method defers instantiation of a class (interface class) to its subclasses.
applicability:
When a class does not know the class of the object it must create. (The factory does not know whether to create product A or product B)
When a class wants its subclasses to specify the objects it creates. (Use factory A and factory B to create products)
When a class delegates the responsibility for object creation to one of multiple helper subclasses, and you want to localize the information about which helper subclass is the delegate.
Class Diagram:
/**
工厂方法模式
/*
// FactoryMethod工厂方法类
public class FactoryMethod{
public static void main(String[] args){
// 创建一个工厂
Factory factoryA = new FactoryA();
// 创建一个产品
Product productA = factoryA.createProduct() // 编译看=左边(是否有对应的方法),运行看=右边(实际是否有对应的方法)
productA.info(); // 具体产品的方法
// 创建一个工厂
Factory factoryB = new FactoryB();
// 创建一个产品
Product productB = factoryB.createProduct()
productB.info(); // 具体产品的方法
}
}
// Product 产品接口
interface Product{
public void info();
}
// ProductA 实现 Product 产品接口
class ProductA implements Product{
// 实现抽象产品类中的抽象方法
@Override
public void info(){
System.out.println("产品A")
}
}
// ProductB 实现 Product 产品接口
class ProductB implements Product{
// 实现抽象产品类中的抽象方法
@Override
public void info(){
System.out.println("产品B")
}
}
// Factory 工厂接口
interface Factory{
public Product createProduct();
}
// FactoryA 实现 工厂接口
class FactoryA implements Factory{
@Override
public Product createProduct(){
return new ProductA();
}
}
// FactoryB 实现 工厂接口
class FactoryB implements Factory{
@Override
public Product createProduct(){
return new ProductB();
}
}