[design pattern] Factory method / Static Factory

什么是静态工厂

我们一般来说使用 new 来创建一个对象,在实际的开发中,还可以通过一个静态方法来提供一个类的instance。

 1     // constructor
 2     Fragment fragment = new MyFragment();
 3     // or
 4     Date date = new Date();
 5 
 6     // static function to provide an instance
 7     Fragment fragment = MyFragment.newIntance();
 8     // or 
 9     Calendar calendar = Calendar.getInstance();
10     // or 
11     Integer number = Integer.valueOf("3");

有什么优势(相比构造函数)

1. Effective Java - 考虑使用静态工厂方法代替构造器

2. 静态工厂方法可以有自己的函数名,构造函数只能和类名一致

3. 不需要每次都创建一个新的对象,可以用一个 HashMap 来缓存 instance。

4. 可以有多个参数相同,但是名称不同的工厂方法。

5. 可以减少对外暴露的属性

如何实现

Sample 1

 1 // LocalDate ld = LocalDateFactory.fromInt(20200202);
 2 
 3 public class LocalDateFactory {
 4 
 5     private static Map<Integer, LocalDate> cache = new HashMap<>();
 6 
 7     public static LocalDate fromInt(int yyyyMMdd) {
 8         if (yyyyMMdd >= 20200101 && yyyyMMdd <= 20301231) {
 9             LocalDate result = cache.get(yyyyMMdd);
10             if (result == null) {
11                 result = create(yyyyMMdd);
12                 cache.put(yyyyMMdd, result);
13             }
14             return result;
15         }
16         return create(yyyyMMdd);
17     }
18 
19     private static LocalDate create(int yyyyMMdd) {
20         return LocalDate.of(yyyyMMdd / 10000, yyyyMMdd / 100 % 100, yyyyMMdd % 100);
21     }
22 }

Sample 2

如果直接使用构造函数的话,无法保证使用者的参数是否合法

1     Player player1 = new Player(Player.TYPE_RUNNER);
2     Player player2 = new Player(Player.TYPE_SWEIMMER);

这样就可以避免以调用问题。

 1 // Player : Version 2
 2 class Player {
 3     public static final int TYPE_RUNNER = 1;
 4     public static final int TYPE_SWIMMER = 2;
 5     public static final int TYPE_RACER = 3;
 6     int type;
 7 
 8     private Player(int type) {
 9         this.type = type;
10     }
11 
12     public static Player newRunner() {
13         return new Player(TYPE_RUNNER);
14     }
15     public static Player newSwimmer() {
16         return new Player(TYPE_SWIMMER);
17     }
18     public static Player newRacer() {
19         return new Player(TYPE_RACER);
20     }
21 }

参考

https://www.jianshu.com/p/ceb5ec8f1174

https://www.liaoxuefeng.com/wiki/1252599548343744/1281319170474017 

 
原文地址:https://www.cnblogs.com/zhangwanying/p/15195606.html