Facebook
From Colorant Penguin, 5 Years ago, written in Java.
Embed
Download Paste or View Raw
Hits: 238
  1. package com.marcosholgado.daggerplayground;
  2.  
  3.  
  4. import android.app.Activity;
  5. import android.os.Bundle;
  6.  
  7. public class PresenterExample {
  8.  
  9.     public interface View {}
  10.  
  11.     public interface Presenter<V extends View> {
  12.         void attachView(V view);
  13.         void detachView();
  14.     }
  15.  
  16.     public class BasePresenter<V extends View> implements Presenter<V> {
  17.  
  18.         V view;
  19.  
  20.         public void attachView(V view) {
  21.             this.view = view;
  22.         }
  23.  
  24.         public void detachView() {
  25.             this.view = null;
  26.         }
  27.     }
  28.  
  29.     // KONKRETNE WIDOKI I PRESENTERY
  30.  
  31.     public interface ViewA extends View {}
  32.  
  33.     public interface PresenterA extends Presenter<ViewA> {
  34.         void whatever();
  35.     }
  36.  
  37.     public class PresenterAImpl extends BasePresenter<ViewA> implements PresenterA  {
  38.         @Override
  39.         public void whatever() {
  40.             //do nothing
  41.         }
  42.     }
  43.  
  44.     // ACTIVITY BAZOWE (Z GENERYKIEM)
  45.  
  46.     public abstract class BaseActivity<P extends Presenter> extends Activity implements View {
  47.         protected P presenter;
  48.  
  49.  
  50.         @Override
  51.         protected void onCreate(Bundle savedInstanceState) {
  52.             super.onCreate(savedInstanceState);
  53.  
  54.             this.presenter.attachView(this); // możesz wołać metody z bazowego interfejsu
  55.         }
  56.  
  57.         @Override
  58.         protected void onDestroy() {
  59.             this.presenter.detachView();
  60.             super.onDestroy();
  61.         }
  62.     }
  63.  
  64.     // Konkretne activity które rozszerza bazowe
  65.  
  66.     public class ActivityA extends BaseActivity<PresenterA> {
  67.         @Override
  68.         protected void onCreate(Bundle savedInstanceState) {
  69.             this.presenter = new PresenterAImpl(); // tu tworzysz konkretny presenter
  70.             super.onCreate(savedInstanceState);
  71.             presenter.whatever(); // możesz zawołać, bo wiesz, że `onAttach` już się wywował w base
  72.         }
  73.     }
  74.  
  75. }