16
RoboGuice well-known DI framework for Android 5/7/2011 1 Android May Days 2011

RoboGuice

Embed Size (px)

DESCRIPTION

Presentation about RoboGuice for Android.

Citation preview

Page 1: RoboGuice

RoboGuicewell-known DI framework for Android

5/7/2011 1Android May Days 2011

Page 2: RoboGuice

Dependency Injection• Устранение зависимостей в коде

• Замена паттерна new()

• Избавление от рутины создания фабрик, заводов

и цехов

• Возможность использования нескольких

конфигураций

• Ограничение кол-ва инстанций класса

• Упрощение тестирования

5/7/2011Android May Days 2

Page 3: RoboGuice

RoboGuice• http://code.google.com/p/roboguice/

• Первым делом, это DI фрэймворк,

который также позволяет:o @InjectView()

o @InjectResource()

o @InjectPreference()

o @Inject System Services

o @Observes Events

5/7/2011I’m footer and nobody reads me 3

Page 4: RoboGuice

Injecting RoboGuice• Скачать RoboGuice 1.1.1 и guice-2.0-no_aop.jar и

подключить их к проекту. Или есть прекрасная

возможность начать пользоваться Maven’ом

(чего я еще не сделал)

• Добавить в проект класс наследник

RoboApplication и прописать его в

AndroidManifest.xlm в тэге application значением

параметра android:name (“.MyRoboApplication”)

5/7/2011Damn footer live 4

Page 5: RoboGuice

Application Code Sample

5/7/2011I’m a poop-poor footer, no one likes me 5

public class DiscoBoxApplication extends RoboApplication {

@Override

protected void addApplicationModules(List<Module> modules) {

modules.add(new NetSocketModule());

modules.add(new DiscoBoxModule());

super.addApplicationModules(modules);

}

}

Page 6: RoboGuice

Modules• Происходит настройка bind-ингов классов на

конкретные объекты

• Статическая инициализация

5/7/2011I could be a header 6

bind(Client.class).to(SocketClient.class);

@Provides public Client provideClient() {

Client c = new SocketClient();

requestInjection(c);

return c;

}

requestStaticInjection(ClientServiceAPI.class);

Page 7: RoboGuice

Module Sample

5/7/2011footer sample 7

public class NetSocketModule extends AbstractModule {

public static final String SERVER_BROADCAST_IN_PORT =

"SERVER_BROADCAST_IN_PORT";

public static final String SERVER_BROADCAST_OUT_PORT = "BROADCAST_OUT_PORT";

public static final String SO_TIMEOUT = "SO_TIMEOUT";

private static final int SERVER_BROADCAST_IN_PORT_VALUE = 2012;

private static final int SERVER_BROADCAST_OUT_PORT_VALUE = 2013;

private static final int SO_TIMEOUT_VALUE = 20 * 1000;

@Override

protected void configure() {

bind(ProtocolProcessor.class).to(DefaultProtocolProcessor.class);

bind(Connection.class).to(DefaultConnection.class);

bind(Client.class).to(SocketClient.class);

bind(Server.class).to(SocketServer.class).in(Scopes.SINGLETON);

bind(ServerFinder.class).to(SocketServerFinder.class);

bind(Integer.class).annotatedWith(Names.named(SO_TIMEOUT))

.toInstance(SO_TIMEOUT_VALUE);

bind(Integer.class).annotatedWith(Names.named(SERVER_BROADCAST_IN_PORT))

.toInstance(SERVER_BROADCAST_IN_PORT_VALUE);

bind(Integer.class).annotatedWith(Names.named(SERVER_BROADCAST_OUT_PORT))

.toInstance(SERVER_BROADCAST_OUT_PORT_VALUE);

}

}

Page 8: RoboGuice

Injecting• С помощью @Inject

• C помощью Injector

5/7/2011blah-blah-blah 8

@Inject

protected Injector injector;

@Inject

public SocketServer(@Named(NetSocketModule.SERVER_PORT) int port) {

...

}

@Inject

public void setProtocolProcessor(ProtocolProcessor processor) {

this.processor = processor;

}

Connection connection = injector.getInstance(Connection.class);

Page 9: RoboGuice

Lazy Injection• Использование интерфейса Provider<T>

5/7/2011and lazy footer 9

@Inject public Provider<Server> serverProvider;

public void methodRequersServer() {

Server servet = serverProvider.get();

...

}

Page 10: RoboGuice

Scopes• Можно пометить класс аннотацией @Singleton,

для ограничения кол-ва инстанций тяжелого

ресурсоемкого класса

5/7/2011scopes looks like footer friends 10

@Singleton

public class SocketServer implements Server {

...

}

Page 11: RoboGuice

Constructors with params• Использование аннотаций и специальных

биндингов

5/7/2011what footers are good for? 11

@Inject

public SocketServer(@Named(NetSocketModule.SERVER_PORT) int port,

@Named(NetSocketModule.SERVER_BROADCAST_ADDRESS) String broadcastAddress,

@Named(NetSocketModule.SERVER_BROADCAST_IN_PORT) int broadcastInPort,

@Named(NetSocketModule.SERVER_BROADCAST_OUT_PORT) int broadcastOutPort) {

}

@Override

protected void configure() {

...

bind(Integer.class).annotatedWith(Names.named(SERVER_BROADCAST_IN_PORT))

.toInstance(SERVER_BROADCAST_IN_PORT_VALUE);

bind(Integer.class).annotatedWith(Names.named(SERVER_BROADCAST_OUT_PORT))

.toInstance(SERVER_BROADCAST_OUT_PORT_VALUE);

bind(String.class).annotatedWith(Names.named(SERVER_BROADCAST_ADDRESS))

.toInstance(SERVER_BROADCAST_ADDRESS_VALUE);

}

Page 12: RoboGuice

Constructors with params• Использование @Provides в модуле

5/7/2011footer is watching you 12

@Provides Server provideServer() {

Server server = new SocketServer(2011,

"224.0.0.0", 2013, 2014);

requestInjection(server);

return server;

}

Page 13: RoboGuice

Events• Использовать уже готовые событий или написать

свои

5/7/2011footer, simple as is 13

public void performShutDown(@Observes OnDestroyEvent event) {

doSomeCleanUp();

}

@Inject protected EventManager eventManager;

protected void buy() {

eventManager.notify(MyOtherActivity.this, new MyBuyEvent() );

}

protected void handleBuy(@Observes MyBuyEvent buyEvent ) {

Toast.makeToast(this, "You won't regret it!",

Toast.LENGTH_LONG).show();

}

//The event class can be anything you want

public class MyBuyEvent {

...

}

Page 14: RoboGuice

Views• Устранение лишнего, повторяющегося от

активити к активити нудного тупого обезьяньего

кода findViewById(R.id.damn_view_id) в onCreate()

5/7/2011cool footer is not a crime 14

@InjectView(R.id.server_search_button_panel) ViewSwitcher searchButtonSwitcher;

@InjectView(R.id.server_selector) Spinner serverSelector;

@InjectView(R.id.server_search_button) Button searchButton;

@InjectView(R.id.client_music_mode_button) Button musicModuleButton;

Page 15: RoboGuice

Logging• RoboGuice's Ln logger

o Отличный формат вызова

o Автоматическое отключение debug и verbose логов при release-ой

сборке

o В тэге лога сам пишет класс и номер строки кода

o Можно легко переопределить формат отображения и

перенаправить вывод лога в файл

5/7/2011we footers hate each other 15

Ln.d("text");

Ln.d("formatted %s", "text");

Ln.d(exception, "reason %s", "text");

Page 16: RoboGuice

Спасибо за внимание• Презентацию подготовил

Шауберт Александр

[email protected]

Специально для Android May Days 2011

5/7/2011and who will say thanks to footer 16