工厂方法模式
工厂方法是用于创建对象的接口。该接口的具体实现指定要创建的具体对象。
当客户端必须实例化一个对象,但它不应该知道它是如何创建的时,就会使用工厂方法模式。
+------------+ uses +-------------+
| Client | ----------> | Factory |
+------------+ +-------------+
| uses | create() |
V +-------------+
+------------+ ^
| SomeObject | |
+------------+ |
^ |
| |
+--------------------+ create +------------------+
| SomeConcreteObject | <-------- | ConcreateFactory |
+--------------------+ +------------------+
静态工厂方法
静态工厂方法模式是一种编写干净代码的方法。这是一种为构造函数提供更有意义的名称来表达其功能的方法。例如。
List<String> newList = new ArrayList<String>(otherList);
上面的代码是什么意思?
Is newList
的副本otherList
或者是ArrayList
保留一个参考otherList
并且只是将调用委托给它(就像包装器一样)?
我想每个人都知道上面的代码做了什么,因为我们阅读了javadoc。尽管如此,如果使用静态工厂方法,代码会更清晰,而无需阅读javadoc。例如。
List<String> copy = ArrayList.copyOf(otherList);
SortedSet<SomeObject> sortedSet = TreeSet.orderedBy(comparator);
使用静态工厂方法,还可以使用相同的参数列表编写多个“构造函数”,因为您可以给每个人另一个名称。使用“普通”构造函数这是不可能的。例如。
List<String> copy = ArrayList.copyOf(otherList);
List<String> delegateList = ArrayList.delegateOf(otherList);