4 Managing component interactions Role interfaces Mediators Forwarding Proxies Callbacks Events Adapters Factories 1
Removing component dependencies with interfaces A B Unknown to A A IB B how what 2
Role-based interfaces Client1 Services Client2 Client1 Server Role1 Server Client2 Role2 3
Example VisualComponent Button EventSource 4
Fine-grained role interfaces Clients X Y Z Roles A B C D Service providers P's interface P Q Q's interface 5
Managing multi-participant interaction with mediators Set of strongly interacting components Problems: interdependencies are unstructured and difficult to understand distributed behavior between several classes cannot be customized without a lot of subclassing participants cannot be used in other contexts 6
Example 7
Mediator Advantages: limits subclassing decouples objects simplifies communication (one-to-many instead of many-to-many) Problem: centralized control (mediator may become monolithic) 8
Coordinator widgetchange(widget) createwidgets() show() Example ListBox ListBoxI getselected(): str Dialog Coordinator TextField TextFieldI settext(str) Widget changed() Button ButtonI enable() 9
Typical interaction ListBox DialogCoordinator TextField Button widgetchange getselected settext enable 10
Forwarding Unknown to A Bimp opimp() imp A call op op() B A call op op() B imp.opimp(); 11
Forwarding: example Chargable discount(int): int CustomerSupport discount(int): int Account Manager Customer KeyCustomer Support 12
Delegation: Implementing inheritance with forwarding "Collective" Car object printdescription self Car parent Vehicle parent Commodity parent printdescription: {printname;... } 13
Delegation: Implementing inheritance with forwarding "Collective" Car object printdescription self Car parent Vehicle parent Product parent Client parent printdescription: {printname;... } 14
Removing component dependencies with proxies Proxy: a component that represents another component in some activity Client op Proxy op Actual 15
Proxy design pattern Client Services request()... actual.request() Proxy request() actual Server 16
Applications distributed systems (e.g. EJB) lazy loading (e.g. object bases) smart pointers... 17
Navigator Example: lazy loading Map getname() getroute(from,to) actual getroute service provided by a Map return mapname; MapProxy map CityMap if not loaded then map = loadfromfile(); loaded = true end; map->getroute() getname getroute getname getroute 18
Removing use dependencies with callbacks Callback A technique to allow a unit that called a service to receive control during the service. Usually the service belongs to a general-purpose library that should be unaware and independent of the applications calling the services of the library. Callback makes it possible to build general-purpose units that are able to call their users without becoming dependent on them. 19
Control visits the called unit during callback library as a sequence diagram: : Library : Application oper1 service call return callback oper2 oper2 return oper1 return application callback 20
Implementing callbacks using inheritance run() Engine EngineUser warn(str) if (oilpressure<limit) { user.warn();... PowerSource start() stop() setuser(engineuser) myeng = new Engine(); myeng.setuser(this); myeng.start(); Car setup() warn(str)... Platform Application log.output("oil pressure low"); myeng.stop(); 21
Käytetään n poikkeuksia? Voidaanko poikkeuksilla saada periaatteessa aikaan sama kuin takaisinkutsuilla? A Ei koskaan B Joskus harvoin C Usein D Aina 22
Poikkeuksilla Engine start() if (oilpressure<limit) {... throw new Oilpressure(); }... PowerSource start() throws Oilpressure stop() setuser(engineuser) setup():... myeng = new Engine(); myeng.setuser(this); try { myeng.start(); } catch (Oilpressure op) {warn("...");} Erot: Edut: Haitat: Car setup() warn(str)... - ei takaisinkutsurajapintaa - käyttävän yksikön (Car) tulee varautua poikkeukseen - yksinkertaisempi - kirjastoyksikön ei tarvitse tietää mitään käyttävän yksikön operaatioista (edes takaisinkutsurajapintaa) - kankeampi: kirjastoyksikkö ei voi jatkaa tapahtuman käsittelyn jälkeen (tässä tosin ei ilmeisesti tarvitsekaan) - yleisesti vaikea erikoistaa tapahtumaan reagointia (ei tosin tässä esimerkissä) Platform Application log.output(str+": Oil pressure low"); myeng.stop(); 23
Removing dependencies with events An event is a state of things that may occur during the execution of the system, has an identifiable representation in the system, needs response from one or more components in the system. 24
From services to events service caller event source service provider event event observers 25
Using events with GUI GUI User actions State changes Application logic 26
Synchronous callback-based based event handling register Event source Observers notify event (callback) 27
Observer design pattern Observer update(event) Source Component obs src Observer Component Source register(observer) unregister(observer) 28
Event handling in Java: Example ActionListener actionperformed(actionevent) JMenuItem obs src AppComp AbstractButton addactionlistener(actionlistener) 29
Removing interface dependencies with adapters service request in interface A Adapter service request Component 1 in interface B Component 2 Adapter: a software unit between the caller and the callee, allowing the caller to be unaware of the interface of the called. 30
Adapter design pattern AbstractServices request() Client ConcreteServices concrequest()... adaptee.concrequest() Adapter request() adaptee Server 31
Example: Sun's BeanBox 32
Using adapters in event-based communication for independent components registering notify event call service Component Adapter Component 33
BeanBox: a closer look generated adapter class: public class Hookup_1734b2d565 implements java.awt.event.actionlistener, java.io.serializable { public void settarget( sunw.demo.juggler.juggler t) { target = t; } public void actionperformed( java.awt.event.actionevent arg0) { target.stopjuggling(); } When mouse click event occurs, activate stopjuggling-operation } private sunw.demo.juggler.juggler target; 34
Managing creation dependencies with factories FactoryRegistry register(factory) AppInit Factory create(): Product AppFactory Platform <<create>> Product service AppProduct 35
Simple version: Factory Method design pattern Product Creator factorymethod anoperation product = factorymethod();... AppProduct create ConcCreator factorymethod return new AppProduct(); 36
Example <<interface>> Document open() close() use Application createdocument() newdocument() opendocument() doc = createdocument(); docs.add(doc); doc.open(); MyDocument open() close() create MyApplication createdocument() return new MyDocument; 37
Problem: How to guarantee consistent object sets? Application OR BUT NOT: 38
ShapeFac Solution: a single factory object for the family of objects factory class TwoDimFac instance of factory object uses Application create instance of ThreeDimFac factory class 39
Abstract Factory design pattern: Example AbsFactory createbutton(): Button createmenu(): Menu Application WinFactory Button Menu <<create>> WinButton WinMenu 40