문제

I am searching for an elegant solution/pattern for this problem ( pseudo-code ):

public class LoggedInActivity extends Activity {
    @Override
    protected void onCreate(final Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        if (!isUserLoggedIn()) {
         finish();
         startActivity(getLoginActivity());
        }
    }

    ...
}


class MainActivity extends LoggedInActivity {
    @Override
    protected void onCreate(final Bundle savedInstanceState) {
       super.onCreate(savedInstanceState);
       codeThatShouldNotBeExecutedWithoutUser();
    }
}

I am searching for a way to not touch every child-class of LoggedInActivity and do a check there - In an Ideal world I can solve this problem in LoggedInActivity completely - but I do not see a way yet.

도움이 되었습니까?

해결책

A good way to solve this is:

  1. Make LoggedInActivity an abstract class.
  2. Add to it an abstract method:

    abstract void codeThatShouldNotBeExecutedWithoutUser();

  3. Change all subclasses to implement (and override) codeThatShouldNotBeExecutedWithoutUser(). If they already implement that method, you should at least add the @Override annotation to make it clear that the method is being overridden.

  4. Remove the calls to codeThatShouldNotBeExecutedWithoutUser() from all the subclasses.
  5. Change LoggedInActivity.onCreate() to call codeThatShouldNotBeExecutedWithoutUser() if and only if the user is logged in:

    @Override
    protected void onCreate(final Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        if (!isUserLoggedIn()) {
           finish();
           startActivity(getLoginActivity());
        } else {
           codeThatShouldNotBeExecutedWithoutUser();
        }
    }
    
라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top