java中应用

java中继承cloneable接口,可以实现clone;

设计实现

继承同一个父类,父类拥有公共的参数,父类定义抽象方法 clone()子类实现自己的有参、无参构造方法,有参构造方法,有参构造方法传入克隆的目标对象,一方面使用super构造父类,一方面对自己特有的参数赋值,最终clone(),返回new 构造方法(this)

父类-shape

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
package com.lcf.demo.pattern.prototype;

public abstract class Shape {
public int x;

public int y;

public String color;

public Shape(){

}

public Shape(Shape target){
if(target!=null){
this.x=target.x;
this.y=target.y;
this.color=target.color;
}
}

public abstract Shape clone();


}

子类-Cycle

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
package com.lcf.demo.pattern.prototype;

public class Cycle extends Shape{
public int radis;

public Cycle() {
}

@Override
public Shape clone() {
return new Cycle(this);
}

public Cycle(Cycle target){
super(target);
if(target!=null){
this.radis=target.radis;
}
}
}

子类-Retangle

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
package com.lcf.demo.pattern.prototype;

public class Retangle extends Shape{

public int width;

public int height;

public Retangle(){

}
public Retangle(Retangle retangle){
super(retangle);
this.width=retangle.width;
this.height=retangle.height;
}

@Override
public Shape clone() {
return new Retangle(this);
}


}

应用

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
package com.lcf.demo.pattern.prototype;

import java.util.ArrayList;
import java.util.List;

public class Application {
public static void main(String[] args) {
List<Shape> shapeList=new ArrayList<>();
List<Shape> shapeCopy =new ArrayList<>();

Cycle cycle=new Cycle();
cycle.x=1;
cycle.y=2;
cycle.color="red";
cycle.radis=0;
shapeList.add(cycle);

Retangle retangle=new Retangle();
retangle.height=1;
retangle.width=2;
shapeList.add(retangle);

for(Shape shape:shapeList){
shapeCopy.add(shape.clone());
}

for(int i=0;i<shapeList.size();i++){
if(shapeList.get(i)!=shapeCopy.get(i)){
System.out.println("两个对象不同");
}
}

}

}