Smirnov dependency-injection-techforum(1)

574
-1

Published on

0 Comments
0 Likes
Statistics
Notes
  • Be the first to comment

  • Be the first to like this

No Downloads
Views
Total Views
574
On Slideshare
0
From Embeds
0
Number of Embeds
1
Actions
Shares
0
Downloads
5
Comments
0
Likes
0
Embeds 0
No embeds

No notes for slide

Smirnov dependency-injection-techforum(1)

  1. 1. Александр СмирновРуководитель группы разработки, iOS Почтаalex.smirnov@corp.mail.ru@__smirnov__
  2. 2. DEPENDENCY INJECTION@__smirnov__
  3. 3. EVERY SOLUTION NEEDS A PROBLEM@__smirnov__
  4. 4. ПРОБЛЕМЫ@interface Emailer : NSObject {@privateKlingonSpellChecker* spellChecker;}@end@implementation Emailer- (id)init {if(self = [super init])spellChecker = [KlingonSpellChecker new];return self;}@end• Связанный код• Сложно переиспользовать• Не тестируемый• Зависимости скрыты@__smirnov__
  5. 5. РЕШЕНИЯ ДО DEPENDENCY INJECTION•Construction by hand•Factory pattern•ServiceLocator pattern@__smirnov__
  6. 6. CONSTRUCTION BY HAND@__smirnov__
  7. 7. CONSTRUCTION BY HAND- (id)initWithSpellChecker:(id<SpellChecker>) spellChecker; • Нет сокрытия зависимостей • “Тестируемо” • Инъекция ‘руками’, нетвозможности сменить все и сразу • Клиенты сервисов должны знатькак связаны графы объектов- (id)init;@__smirnov__
  8. 8. FACTORY PATTERN@__smirnov__
  9. 9. FACTORY PATTERN@interface EmailerFactory{}- (id<Emailer>) createKlingonEmailer;@end+- (id)initWithSpellChecker:(id<SpellChecker>) spellChecker;@__smirnov__
  10. 10. @interface EmailerFactory{}- (id<Emailer>) createKlingonEmailer;@endFACTORY PATTERN• Нет сокрытия зависимостей• “Тестируемо”• Есть способ сменить всезависимости разом• Сами создаем объекты• Больше сложных зависимостейэто более сложные фабрики• Меняем код, чтобы тестировать• По фабрике на каждый сервис ?@__smirnov__
  11. 11. SERVICE LOCATOR PATTERN[serviceLocator resolveByProtocol: @protocol(Emailer)];[serviceLocator resolveByName: @"KlingonEmailer"];@__smirnov__
  12. 12. SERVICE LOCATOR PATTERNThe key difference is that with a Service Locator every user of aservice has a dependency to the locator.The locator can hidedependencies to other implementations, but you do need to seethe locator. (c) Martin FowlerSo the decision between locator and injector depends on whether thatdependency is a problem.@__smirnov__
  13. 13. THE HOLLYWOOD PRINCIPLE@__smirnov__
  14. 14. THE HOLLYWOOD PRINCIPLEDon’t call us; we’ll call you@__smirnov__
  15. 15. BIG DI BENEFITS•Тестируемый код•Переиспользуемый код•Слабо связанный код•!Scopes!@__smirnov__
  16. 16. INJECTION IDIOMS•Constructor injection•Setter injection•Interface injection•Field injection•Method injection (AOP)NO IMAGE,SORRY@__smirnov__
  17. 17. CONSTRUCTOR INJECTIONПолностью готовый к работе объект@interface SMTPEmailer<Emailer>- (instancetype) initWithSpellchecker:(id<Spellchecker>) spellcheckeraddressbook:(id<AddressBook>) addressbook;@end@interface EmailerClient: NSObject- (instancetype) initWithEmailer:(id<Emailer>) emailer;@end@__smirnov__
  18. 18. SETTER INJECTION@interface SMTPEmailer<Emailer>@property(nonatomic, strong) id <Spellchecker> spellchecker;@property(nonatomic, strong) id <AddressBook> addressbook;@endМожем модифицировать зависимостиМожем получить полусобранный объектМожем намеренно не предоставлять часть зависимостей@__smirnov__
  19. 19. METHOD INJECTION (AOP)- (void) sendLetterWithSubject:(NSString*) subjecttext:(NSString*) text {NSLog(@"enter sendLetterWithSubject");// do some real workNSLog(@"exit sendLetterWithSubject");}@__smirnov__
  20. 20. BEYONDTHE SCOPE• Singleton scope• Transition objects, no scopeGENERAL PURPOSE SCOPES• Request scope• Session scope• ...APPLICATION LEVEL SCOPES@__smirnov__
  21. 21. SINGLETON SCOPE- (id) init {return self = [super init];}- (void) doSomeWork {[[Emailer sharedInstance] sendEmail];}- (id) initWithEmailer:(id<Emailer>) emailer {if(self = [super init])_emailer = emailer;return self;}- (void) doSomeWork {[_emailer sendEmail];}@__smirnov__
  22. 22. DOMAIN-SPECIFIC SCOPE@interface SMTPEmailer<Emailer>- (instancetype) initWithAccount:(Account*) account;@end@__smirnov__
  23. 23. IOS DEPENDENCY INJECTIONМыши плакали, кололись, но все равно продолжали есть кактус@__smirnov__
  24. 24. ALWAYS ALMOST GUICE•“Annotation” Based DependencyInjection•Custom Object Providers•Protocol Bindings•Instance Bindings•Lazily instantiates dependenciesObjection orTyphoon•All above (except “annotation”)+•!Autowiring!•Assembling with blocks or XML•AppCode integration@__smirnov__
  25. 25. MATERIALS USED• Inversion of Control Containers and the Dependency Injectionpattern by Martin Fowler• Dependency Injection by Dhanji R. Prasanna ( author of Guice )• Design Patterns: Dependency Injection by Griffin Caprio( MSDN Magazine, September 2005 )• Big Modular Java with Guice ( Google I/O 2009 )• Dependency Injection ( !Wikipedia! )@__smirnov__
  26. 26. @__smirnov__

×