简体   繁体   中英

What is suitable pattern for two classes which have difference in one class variable only?

In details. In this question i've used simple example. But in real life, there is huge logic in methods with difference in one state variable only. Example. I have two classes which have method with the same logic. Difference between these two classes is in class variable which used in method.

class A {
    private String str = "A";
    void method() {
        System.out.print(str);
    }
}

class B {
    private String str = "B";
    void method() {
        System.out.print(str);
    }
}

I suppose using inheritance i can achieve the result.

abstract class Abs {
    void method() {
        System.out.print(getStr());
    }
    abstract String getStr();
}

class A extends Abs {
    String getStr() {
        return "A";
    }
}

class B extends Abs {
    String getStr() {
        return "B";
    }
}

Is it good solution? Or there are any others, or maybe design-patterns to achieve my goal? Thanks in advance.

If it's just a difference in value, they should just be two instances of the same class.

I would just pass the "variable" data to the constructor and be done with it.

class A {
    private String str;

    public A(String str) {
        this.str = str;
    }

    public void method() {
        System.out.print(str);
    }
}

Then when using it

A a = new A("a");
A b = new A("b");
a.method(); // prints "a"
b.method(); // prints "b"

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