许多时候,我们的子类都拥有相同的父类,有时候,我们想要子类之间的值能够相互共享,那么就可以通过下面的方式实现了。
思路:
1、给父类加一个type字段,用来区分是父类自己的对象还是子类对象。
2、在子类1set值时,如果type为page时,给父类赋值。
3、在子类2get值时,如果type为page时,得到父类的值。
代码
父类
@Data
@NoArgsConstructor
@RequiredArgsConstructor
public class ParentData {
/**
* 父类类型,page,view
*/
@NonNull
private String type;
/**
* 父类值
*/
private String value;
/**
* 父类对象
*/
private ParentData parentData;
public String getValueByType(){
if(type.equals("page")){
return value;
}
return parentData==null?"":parentData.getValueByType();
}
public void setValueByType(String value){
if(type.equals("page")){
this.value=value;
}else{
if(parentData!=null){
parentData.setValueByType(value);
}
}
}
}
子类1
public class ChildrenData1 extends ParentData{
public ChildrenData1(){
super("view");
}
}
子类2
public class ChildrenData2 extends ParentData{
public ChildrenData2(){
super("view");
}
}
main方法
public class testMain {
public static void main(String[] args) {
ParentData parentData=new ParentData("page");
ChildrenData1 childrenData1=new ChildrenData1();
childrenData1.setParentData(parentData);
childrenData1.setValueByType("我是子类1传入的值");
System.out.println(childrenData1.getValueByType());
System.out.println(childrenData1.getValue());
ChildrenData2 childrenData2=new ChildrenData2();
childrenData2.setParentData(parentData);
System.out.println(childrenData2.getValueByType());
System.out.println(childrenData2.getValue());
}
}
输出: