static 변수를 클래스마다 상속하기.

Tags:

템플릿을 사용한 클래스별 static 변수의 상속

I made an ugly code to solve the problem in JAVA. (Not to metion of instantiation. I know. I’ve violated the rule.)

Better Idea?

BTW, you should not use Thread.currentThread() or populate exception by your self. They are very sl~~~ow methods in Java. So, do not use them in this problem.

No singleton. Just subclassing is allowed.

I guess there is no way in JAVA if I can not use Thread.currentThread() or exception.

———————————-


import java.util.*;
public class StaticForEachClass {
    
    private static Hashtable<Class<? extends StaticForEachClass>, 
        Integer> fStaticVarTable
        = new Hashtable<Class<? extends StaticForEachClass>, 
            Integer>();

    public void setValue(int v) {
        fStaticVarTable.put(getClass(), v);
    }
    
    public int getValue() {
        return fStaticVarTable.get(getClass());
    }
}


class A extends StaticForEachClass {
    
    
}


class B extends StaticForEachClass {
    
}

class App {
    public static void main(String[] args) {
        
        A a = new A();
        a.setValue(1);
        System.out.println("A.getValue(): " + a.getValue());
        
        B b = new B();
        b.setValue(2);
        System.out.println("B.getValue(): " + b.getValue());
        System.out.println("A.getValue(): " + a.getValue());
    }
}

Comments

2 responses to “static 변수를 클래스마다 상속하기.”

  1. 민구 Avatar
    민구

    감사~.. 그 Monostate 패턴 글은 전에도 봤는데..

    생각 좀 해봤는데, C++과 같은 그런 방식은
    불가능할거 같아요..

    모노 스테이트도 결국 인스턴스 메소드로
    하는거라서.. 그냥 흥미삼아서 static 메소드로
    하고 싶거든요.

  2. 민구 Avatar
    민구

    참 그리고..
    전 비슷한 시기에 출간된
    J2EE Design Patterns를 사버리고 말았죠.

    돈이 딸려서.. ㅠㅠ

Leave a Reply

Your email address will not be published. Required fields are marked *