count class instances for every derived class

前端 未结 7 2057
栀梦
栀梦 2021-02-19 09:09

is there any way to make all derived classes count their instances?How (write code in one of C++, C#, Java)?

Imagine I\'ve got access to the root class (e.g. object), an

7条回答
  •  离开以前
    2021-02-19 09:40

    In Java you can implement the counting function to the common super class of your hirachy.

    This base class contains a Map - associating the classes to the number of instances. If a instance of base or one of its sub class is created, then the constructor ins invoked. The constructor increase the number of instances of the concreate class.

    import java.util.Map.Entry;
    import java.util.concurrent.ConcurrentHashMap;
    import java.util.concurrent.ConcurrentMap;
    import java.util.concurrent.atomic.AtomicInteger;
    
    public class Base {
    
        /** Threadsave counter */
        private static final ConcurrentMap, AtomicInteger>
           instancesByClass 
           = new ConcurrentHashMap, AtomicInteger>(
                10);
    
        /** The only one constructor of base */
        public Base() {
            Class concreateClass = this.getClass();
            AtomicInteger oldValue = instancesByClass.putIfAbsent(concreateClass,
                    new AtomicInteger(1));
            if (oldValue != null) {
                oldValue.incrementAndGet();
            }
        }
    
        /* DEMO starts here */
        public static class SubA extends Base{
        }
    
        public static class SubB extends Base{
        }
    
        public static class SubSubA extends SubA{
        }
    
    
        public static void main(String[] args) {
            printNumbers();
            new SubA();
            new SubA();
    
            new SubB();
    
            new SubSubA();
    
            printNumbers();
        }
    
        private static void printNumbers() {
            // not thread save!
            for (Entry, AtomicInteger> item : instancesByClass
                    .entrySet()) {
                System.out.println(item.getKey().getName() + "  :  "
                        + item.getValue());
            }
        }
    }
    

提交回复
热议问题