Conditional calling using static factory method

50 Views Asked by At

This is my project structure. I'm trying to use a static factory function to check for an object and then perform some operations. I followed the this process.

Parent Class:

public abstract class Parent {

    protected static Child1DTO ch1;
    protected static Child2DTO ch2;

    public Parent(Child1DTO ch1) {
        this.ch1 = ch1;
    }

    public Parent(Child2DTO ch2) {
        this.ch2 = ch2;
    }

    protected Parent() {

    }

    public static Child1DTO getCh1() {
        return ch1;
    }

    public static Child2DTO getCh2() {
        return ch2;
    }

    public static Class<?> childType(Object obj) {

        if (obj instanceof Child1DTO) {
                    //do something
            return Child1DTO.class;
        } else if (obj instanceof Child2DTO) {
                    //do something
            return Child2DTO.class;
        }
        return null;
    }
}

Child1DTO Class:

public class Child1DTO extends Parent {

    private String fName1;
    private String lName1;

    public String getfName1() {
        return fName1;
    }
    public void setfName1(String fName1) {
        this.fName1 = fName1;
    }
    public String getlName1() {
        return lName1;
    }
    public void setlName1(String lName1) {
        this.lName1 = lName1;
    }
}

Child2DTO Class:

public class Child2DTO extends Parent{

    private String fName2;
    private String lName2;

    public String getfName2() {
        return fName2;
    }
    public void setfName2(String fName2) {
        this.fName2 = fName2;
    }
    public String getlName2() {
        return lName2;
    }
    public void setlName2(String lName2) {
        this.lName2 = lName2;
    }
}

Child Class:

public class Child extends Parent {

    public Child(Child1DTO ch1) {
        super(ch1);
    }

    public Child(Child2DTO ch2) {
        super(ch2);
    }

    public static Child test(Object obj) {

        if (obj instanceof Child1DTO) { //is this the correct way to check?
            //do something
            return new Child((Child1DTO) obj);
        } else if (obj instanceof Child2DTO) {//is this the correct way to check?

            //do something
            return new Child((Child2DTO) obj);
        }
        return null;
    }

    public static void main(String args[]) {


        if(childType(ch1).equals(ch1)){
            //do something
        }else if(childType(ch2).equals(ch2)){
            //do something
        }else{
            System.out.println("Failed!");
        }
  }

}

EDIT:

Parent class has one Child class and two DTOs Child1DTO and Child2DTO.

  1. Do I need to implement conditional check in Parent class or Child class?
  2. How to achieve conditional check with constructors?
0

There are 0 best solutions below