Showing posts with label Inner class. Show all posts
Showing posts with label Inner class. Show all posts

Wednesday, February 20, 2013

Java에서 function pointer, member function pointer, callback와 같은것 구현하기

보통 UI시스템을 만들 때 주로 사용하는 것이 콜백 함수입니다. 예를 들어서 버튼을 하나 만들고 이 버튼이 클릭 되었을 때 처리하는 바인딩 코드를 내가 원하는 어떠한 함수를 호출하게 하기 위해서 콜백을 사용하지요.

제가 DeadEngine을 만들 때는 멤버 함수 포인터를 이용해서 이를 구현했습니다. 그리고 최근에 안드로이드 작업하면서 자바를 사용하게 되었는데 (자바는 아주 옛날에 써보고 최근에는 거의 안써본...) 자바에는 함수 포인터를 사용할 수가 없습니다. 하지만 Inner class를 이용해서 이것이 구현 가능 합니다. 이 글을 참고하면 됩니다.

http://www.devx.com/tips/Tip/5849

// 사라질까봐 내용 복사. (원문에 대한 저작권은 Ajit Sagar가 가집니다.)


Java's Alternative to Function Pointers

Although Java borrows a lot of concepts and syntax from C++, it also leaves out some of C++'s main features to meet its goal of simplicity. For example, Java excluded memory pointers and function pointers from its arsenal. Function pointers allow flexibility in method invocation at run time. A pointer to the function that needs to be called can be passed in as an argument to the calling function. A method can "call back" another method that is specified as one of its arguments.The inner class construct in JDK 1.1 provides a novel approach to achieve the same goal that function pointers achieve in C++. Anonymous classes in method invocations allow a dynamically defined class to be passed in as a parameter. As a result, the calling class can invoke a method on this class. For example:
 
1.     interface CallbackIfc {
2.       public void callMe();
3.     }
4. 
5.     // This class calls a method on class B.
6.     public class CallbackTester {
7.       CallerClass cc = new CallerClass();
8. 
9.       public void sendCallback() {
10.         cc.callback (new CallbackIfc() {     
11.                        public void callMe() {
12.                          // Implementation code here
13.                        }
14.                      }
15.                    );
16.         }
17.     }
18. 
19. // This class calls back a method on class CallbackIfc.
20. class CallerClass {
21.   public void callback (CallbackIfc c) {
22.     c.callMe();
23.   }
24. }
Lines 1-3 define a new interface called CallbackIfc to be used as a callback class. CallbackIfc defines a single method (callMe()). Lines 20-24 define a class called CallerClass that will exercise the callback. CallerClass has a single method (callback()) that calls a method (callMe()) on an object of the class CallbackIfc. This object is passed in as an argument. Lines 5-17 define the class that invokes callback() on the class CallerClass. It defines a single method (sendCallback()) that calls the method callback() on an object of the class CallerClass. Note that it defines an instance of the interface CallbackIfc within the parentheses. This defines an anonymous class that implements the interface CallbackIfc.


Monday, February 4, 2013

Inner class를 이용해 Attribute와 변수를 구분하기

게임에서 사용되는 유닛이나 무기 정보들은 보통 DB에 저장하고 게임에서는 이를 참고해서 로직을 작성하게 됩니다. 이때 클래스 내부에 DB정보를 저장하고 이를 로직에서 사용할 때 private로 변수를 선언하게 되더라도 이를 로직에서 사용할 때 변경이 되어도 되는 변수인지 아닌지 헷갈릴 때가 많은데요.

가령 mFireRate와 같은 변수가 DB에서 얻은 값이고 이 값을 이용해서 다음과 같은 로직이 있다고 칩니다.

mCount++;

if ( mCount >= mFireRate )
{
then fire it.
}

문제는 mFireRate가 DB변수값인지 아닌지 변수명 자체로는 구분하기가 힘들다는 점입니다. 이것을 해결하기 위해서 mFireRateDB와 같이 변수명에 구분을 하기 위한 접두어나 접미사를 써주는 경우가 있는데 이것 역시 마음에 드는 방식은 아닙니다. 해서... 저는 보통 Inner struct, class를 사용해서 다음과 같이 사용합니다.

class Attribute
{
    int mFireRate;
} mAttrib;

이렇게 하면 앞서 살펴본 코드가 다음과 같이

mCount++;

if ( mCount >= mAttrib.mFireRate )
{
then fire it
}

구분할 수 있게 됩니다. 그렇게 되면 저는 mCount보다는 다음과 같이 변수명을 바꿀 것입니다.


mFireRate++;

if ( mFireRate >= mAttrib.mFireRate )
{
fire it
}

Attribute안에 들어간 값은 읽기 전용이라고 생각하면 코드를 볼 때 더 이해하기가 쉽습니다. 물론 메소드로 표현하면 더 괜찮겠지만 코드 작성하는게 좀 귀찮긴 하지요 :)


mFireRate++;

if ( mFireRate >= mAttrib.GetFireRate() )
{
fire it
}


Task in UnrealEngine

 https://www.youtube.com/watch?v=1lBadANnJaw