# 工厂方法模式
# 简介
创建型模式,解决简单工厂模式中,新增实现类,需要更改工厂类的问题。符合开闭原则,当需要新增一个实现时,新增一个具体的工厂和一个具体的实现即可。
# 示例
public interface Product {
void doSomeThing();
}
public class Product_A implements Product{
@Override
public void doSomeThing() {
System.out.println("A do some thing");
}
}
public class Product_B implements Product{
@Override
public void doSomeThing() {
System.out.println("B do some thing");
}
}
public class Product_C implements Product{
@Override
public void doSomeThing() {
System.out.println("C do some thing");
}
}
public interface Factory {
Product createProduct();
}
public class Product_A_Factory implements Factory{
@Override
public Product createProduct() {
return new Product_A();
}
}
public class Product_B_Factory implements Factory{
@Override
public Product createProduct() {
return new Product_B();
}
}
public class Product_C_Factory implements Factory{
@Override
public Product createProduct() {
return new Product_C();
}
}
# 调用
@Test
public void tt(){
Product product_A = new Product_A_Factory().createProduct();
product_A.doSomeThing();
Product product_B = new Product_B_Factory().createProduct();
product_B.doSomeThing();
Product product_C = new Product_C_Factory().createProduct();
product_C.doSomeThing();
}
# 优化
工厂方法模式,一般不建议暴露工厂方法,如上面的:createProduct,工厂接口改为:
public interface Factory{
Product createProduct();
default void doSomeThing() {
createProduct().doSomeThing();
}
}
调用:
@Test
public void tt2(){
new Product_A_Factory().doSomeThing();
new Product_B_Factory().doSomeThing();
new Product_C_Factory().doSomeThing();
}
# 优化2
不暴露工厂方法,工厂接口优化:
public interface Factory extends Product{
Product createProduct();
@Override
default void doSomeThing() {
createProduct().doSomeThing();
}
}