简体   繁体   中英

what should be the relationship between those classes?

I wish just call Type.getNo() method to get some calculation result. If if if then else block in the Type.getNo() says "take data from TypeX.getNo() ", then TypeX.getNo() is called internally; afterwards, result of it will be sent to Type.getNo() , and from then, Type.getNo() will return the value to the user. In the second case, result of TypeY.getNo() will be used.

For class relationship, what should be the relationship between those classes? I thought it seems to extends relation but, I am a bit confused about how to implement the scenario. To advance my project, should I use Design Pattern to implement this? If yes, which design pattern is appropriate for this case? I feel chain of responsibility looking like to fix, but in chain of responsibility , decision is done on the third class which is, in my case, it should be in the other package. On the other hand, all decision should be done in the same class. Just return value is going to be available in other packages.

                        |--------------------|
                        |       Type         |
                        |--------------------|
                        |    +getNo():int    |
                        |                    |
                        |--------------------|



  |------------------|                    |----------------------|
  |      TypeX       |                    |        TypeY         |
  |------------------|                    |----------------------|
  |                  |                    |                      |
  |  +getNo():int    |                    |      +getNo():int    |
  |                  |                    |                      |
  |------------------|                    |----------------------|

     TypeX and TypeY are visible to only to other classes in the same package

Use an abstract class Type and two classes TypeX , TypeY which extend Type .

Type

abstract class Type {

    int no;

    int getNo() {
        return no;
    }
}

TypeX

public class TypeX extends Type {

    public TypeX(int no) {
        this.no = no;
    }

    @Override
    int getNo() {
        System.out.println("TypeX.getNo()");
        return no;
    }
}

TypeY

public class TypeY extends Type {

    public TypeY(int no) {
        this.no = no;
    }

    @Override
    int getNo() {
        System.out.println("TypeY.getNo()");
        return no;
    }
}

App

public class App {

    public static void main(String[] args) {
        Type x = new TypeX(1);
        Type y = new TypeY(2);

        System.out.println(x.getNo());
        System.out.println(y.getNo());
    }
}

Output:

TypeX.getNo()
1
TypeY.getNo()
2

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM