设计模式——工厂模式

介绍:

工厂模式(Factory Pattern)是 Java 中最常用的设计模式之一。这种类型的设计模式属于创建型模式,它提供了一种创建对象的最佳方式。
在工厂模式中,我们在创建对象时不会对客户端暴露创建逻辑,并且是通过使用一个共同的接口来指向新创建的对象。

工厂模式分类:

  1. 简单工厂(Simple Factory)模式,又称静态工厂方法模式(Static Factory Method Pattern)
  2. 工厂方法(Factory Method)模式,又称多态性工厂(Polymorphic Factory)模式
  3. 抽象工厂(Abstract Factory)模式,又称工具箱(Kit 或Toolkit)模式

简单工厂模式:

适用场景

  • 工厂类负责创建的对象比较少:由于创建的对象较少,不会造成工厂方法中的业务逻辑太过复杂
  • 客户端只知道传入工厂类的参数,对于如何创建对象不关心:客户端既不需要关心创建细节,甚至连类名都不需要记住,只需要知道类型所对应的参数。

例子

假设一家工厂,生产电视,汽车等等,我们先为所有产品定义一个共同的产品接口

1
2
public interface Product {
}

然后工厂的产品实现这个接口

1
2
3
4
5
6
7
8
9
10
public class Tv implements Product {
public Tv(){
System.out.println("product Tv");
}
}
public class Car implements Product {
public Car(){
System.out.println("product Car");
}
}

创建工厂

1
2
3
4
5
6
7
8
9
10
11
12
public class ProductFactory {
public static Product produce(String productName) {
switch (productName) {
case "tv":
return new Tv();
case "car":
return new Car();
default:
return null;
}
}
}

这样的实现有个问题,如果我们新增产品类的话,需要不断的在工厂类中新增case,这样需要修改的地方比较多,所以利用反射来优化。

1
2
3
4
5
6
7
8
9
10
11
public class ProductFactory2 {
public static Product produce(String className) {
try {
Product product = (Product) Class.forName(className).newInstance();
return product;
} catch (Exception e) {
e.printStackTrace();
return null;
}
}
}
分享到: