原型模式在其他框架源码中也有广泛的应用。
Retrofit
众所周知Retrofit是OkHttp的扩展,因此Retrofit的Call接口也像OkHttp的Call类一样实现了原型模式。Call与原型模式有关的代码如下:
public interface Call<T> extends Cloneable {
// ……代码省略……
/**
* Create a new, identical call to this one which can be enqueued or executed even if this call
* has already been.
*/
Call<T> clone();
}
Call的子类OkHttpCall与原型模式有关的源码如下:
final class OkHttpCall<T> implements Call<T> {
// ……代码省略……
@SuppressWarnings("CloneDoesntCallSuperClone") // We are a final type & this saves clearing state.
@Override
public OkHttpCall<T> clone() {
return new OkHttpCall<>(requestFactory, args, callFactory, responseConverter);
}
}
Gson的Excluder类
Gson的Excluder类与原型模式有关的源码如下:
public final class Excluder implements TypeAdapterFactory, Cloneable {
// ……代码省略……
@Override protected Excluder clone() {
try {
return (Excluder) super.clone();
} catch (CloneNotSupportedException e) {
throw new AssertionError(e);
}
}
public Excluder withVersion(double ignoreVersionsAfter) {
Excluder result = clone();
result.version = ignoreVersionsAfter;
return result;
}
public Excluder withModifiers(int... modifiers) {
Excluder result = clone();
result.modifiers = 0;
for (int modifier : modifiers) {
result.modifiers |= modifier;
}
return result;
}
public Excluder disableInnerClassSerialization() {
Excluder result = clone();
result.serializeInnerClasses = false;
return result;
}
public Excluder excludeFieldsWithoutExposeAnnotation() {
Excluder result = clone();
result.requireExpose = true;
return result;
}
public Excluder withExclusionStrategy(ExclusionStrategy exclusionStrategy,
boolean serialization, boolean deserialization) {
Excluder result = clone();
// ……代码省略……
return result;
}
// ……代码省略……
}
可见Gson的Excluder类不但采用了原型模式,而且很多方法中,还使用clone()方法生成新的实例,非常节省资源。
Protobuf-Java
Protobuf-Java的MessageLite.Builder类与原型模式有关的代码如下:
public interface MessageLite extends MessageLiteOrBuilder {
// ……代码省略……
interface Builder extends MessageLiteOrBuilder, Cloneable {
// ……代码省略……
/**
* Clones the Builder.
*
* @see Object#clone()
*/
Builder clone();
}
}
Glide的TransitionOptions
Glide是Android专用的框架,其他方向的读者到此可以跳过。
Glide的TransitionOptions类是用于决定你的加载完成时会发生什么的过渡选项,比如View淡入等。TransitionOptions与原型模式相关的源码如下:
public abstract class TransitionOptions<
CHILD extends TransitionOptions<CHILD, TranscodeType>, TranscodeType>
implements Cloneable {
// ……代码省略……
@SuppressWarnings({
// cast to CHILD is safe given the generic argument represents the object's runtime class
"unchecked",
// CHILD is the correct class name.
"PMD.CloneMethodReturnTypeMustMatchClassName",
// we don't want to throw to be user friendly
"PMD.CloneThrowsCloneNotSupportedException"
})
@Override
public final CHILD clone() {
try {
return (CHILD) super.clone();
} catch (CloneNotSupportedException e) {
throw new RuntimeException(e);
}
}
}