k8s源码设计模式之Clone

原型模式是一种创建型设计模式, 使你能够复制已有对象, 而又无需使代码依赖它们所属的类。

k8s使用代码生成的方式为每个资源对象实现了DeepCopy()方法。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
// pkg/apis/core/types.go
// Pod的定义
// Pod is a collection of containers, used as either input (create, update) or as output (list, get).
type Pod struct {
metav1.TypeMeta
// +optional
metav1.ObjectMeta

// Spec defines the behavior of a pod.
// +optional
Spec PodSpec

// Status represents the current information about a pod. This data may not be up
// to date.
// +optional
Status PodStatus
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
// newPod := pod.DeepCopy()可以调用DeepCopy()复制一个对象
// pkg/apis/core/zz_generated.deepcopy.go
func (in *Pod) DeepCopy() *Pod {
if in == nil {
return nil
}
out := new(Pod)
in.DeepCopyInto(out)
return out
}
func (in *Pod) DeepCopyInto(out *Pod) {
*out = *in
out.TypeMeta = in.TypeMeta
in.ObjectMeta.DeepCopyInto(&out.ObjectMeta)
in.Spec.DeepCopyInto(&out.Spec)
in.Status.DeepCopyInto(&out.Status)
return
}

REF:
1.pkg/apis/core/types.go
2.pkg/apis/core/zz_generated.deepcopy.go