singleton and inheritance in Java

前端 未结 6 604
鱼传尺愫
鱼传尺愫 2021-01-17 16:30

I have a base class that captures some functionality common to two classes. In other words, I can create one base class and make these two classes subclasses of that base cl

6条回答
  •  挽巷
    挽巷 (楼主)
    2021-01-17 16:55

    I don't know if you need an example but I gave it a try. Without knowing any of your details this example is very vague. I am also here to learn so let us know what you end up implementing.

    The Base class:

      public abstract class BaseClass {
    
            public void someMethod() {
                System.out.println("base class hello: " + this);
            }
    
            public abstract void someOtherMethod(String value);
        }
    

    One of the subclasses:

    public class SubClassOne extends BaseClass {
    
        private static SubClassOne instance;
    
        private SubClassOne() {}
    
        public static SubClassOne getInstance() {
            if (instance == null) {
                instance = new SubClassOne();
            }
            return instance;
        }
    
        public void someOtherMethod(String value) {
            someMethod();
            System.out.println("sub class hello: " + value + " " + this);
        }
    
        public static void main(String[] args) {
            SubClassOne one = SubClassOne.getInstance();
            SubClassOne two = SubClassOne.getInstance();
            SubClassOne three = SubClassOne.getInstance();
            SubClassOne four = SubClassOne.getInstance();
            one.someOtherMethod("one");
            two.someOtherMethod("two");
            three.someOtherMethod("three");
            four.someOtherMethod("four");
        }
    }
    

提交回复
热议问题