• Share
  • Email
  • Embed
  • Like
  • Save
  • Private Content
Smirnov dependency-injection-techforum(1)
 

Smirnov dependency-injection-techforum(1)

on

  • 555 views

 

Statistics

Views

Total Views
555
Views on SlideShare
475
Embed Views
80

Actions

Likes
0
Downloads
4
Comments
0

1 Embed 80

http://techforum.mail.ru 80

Accessibility

Categories

Upload Details

Uploaded via as Adobe PDF

Usage Rights

© All Rights Reserved

Report content

Flagged as inappropriate Flag as inappropriate
Flag as inappropriate

Select your reason for flagging this presentation as inappropriate.

Cancel
  • Full Name Full Name Comment goes here.
    Are you sure you want to
    Your message goes here
    Processing…
Post Comment
Edit your comment

    Smirnov dependency-injection-techforum(1) Smirnov dependency-injection-techforum(1) Presentation Transcript

    • Александр СмирновРуководитель группы разработки, iOS Почтаalex.smirnov@corp.mail.ru@__smirnov__
    • DEPENDENCY INJECTION@__smirnov__
    • EVERY SOLUTION NEEDS A PROBLEM@__smirnov__
    • ПРОБЛЕМЫ@interface Emailer : NSObject {@privateKlingonSpellChecker* spellChecker;}@end@implementation Emailer- (id)init {if(self = [super init])spellChecker = [KlingonSpellChecker new];return self;}@end• Связанный код• Сложно переиспользовать• Не тестируемый• Зависимости скрыты@__smirnov__
    • РЕШЕНИЯ ДО DEPENDENCY INJECTION•Construction by hand•Factory pattern•ServiceLocator pattern@__smirnov__
    • CONSTRUCTION BY HAND@__smirnov__
    • CONSTRUCTION BY HAND- (id)initWithSpellChecker:(id<SpellChecker>) spellChecker; • Нет сокрытия зависимостей • “Тестируемо” • Инъекция ‘руками’, нетвозможности сменить все и сразу • Клиенты сервисов должны знатькак связаны графы объектов- (id)init;@__smirnov__
    • FACTORY PATTERN@__smirnov__
    • FACTORY PATTERN@interface EmailerFactory{}- (id<Emailer>) createKlingonEmailer;@end+- (id)initWithSpellChecker:(id<SpellChecker>) spellChecker;@__smirnov__
    • @interface EmailerFactory{}- (id<Emailer>) createKlingonEmailer;@endFACTORY PATTERN• Нет сокрытия зависимостей• “Тестируемо”• Есть способ сменить всезависимости разом• Сами создаем объекты• Больше сложных зависимостейэто более сложные фабрики• Меняем код, чтобы тестировать• По фабрике на каждый сервис ?@__smirnov__
    • SERVICE LOCATOR PATTERN[serviceLocator resolveByProtocol: @protocol(Emailer)];[serviceLocator resolveByName: @"KlingonEmailer"];@__smirnov__
    • 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__
    • THE HOLLYWOOD PRINCIPLE@__smirnov__
    • THE HOLLYWOOD PRINCIPLEDon’t call us; we’ll call you@__smirnov__
    • BIG DI BENEFITS•Тестируемый код•Переиспользуемый код•Слабо связанный код•!Scopes!@__smirnov__
    • INJECTION IDIOMS•Constructor injection•Setter injection•Interface injection•Field injection•Method injection (AOP)NO IMAGE,SORRY@__smirnov__
    • CONSTRUCTOR INJECTIONПолностью готовый к работе объект@interface SMTPEmailer<Emailer>- (instancetype) initWithSpellchecker:(id<Spellchecker>) spellcheckeraddressbook:(id<AddressBook>) addressbook;@end@interface EmailerClient: NSObject- (instancetype) initWithEmailer:(id<Emailer>) emailer;@end@__smirnov__
    • SETTER INJECTION@interface SMTPEmailer<Emailer>@property(nonatomic, strong) id <Spellchecker> spellchecker;@property(nonatomic, strong) id <AddressBook> addressbook;@endМожем модифицировать зависимостиМожем получить полусобранный объектМожем намеренно не предоставлять часть зависимостей@__smirnov__
    • METHOD INJECTION (AOP)- (void) sendLetterWithSubject:(NSString*) subjecttext:(NSString*) text {NSLog(@"enter sendLetterWithSubject");// do some real workNSLog(@"exit sendLetterWithSubject");}@__smirnov__
    • BEYONDTHE SCOPE• Singleton scope• Transition objects, no scopeGENERAL PURPOSE SCOPES• Request scope• Session scope• ...APPLICATION LEVEL SCOPES@__smirnov__
    • 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__
    • DOMAIN-SPECIFIC SCOPE@interface SMTPEmailer<Emailer>- (instancetype) initWithAccount:(Account*) account;@end@__smirnov__
    • IOS DEPENDENCY INJECTIONМыши плакали, кололись, но все равно продолжали есть кактус@__smirnov__
    • 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__
    • 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__
    • @__smirnov__