560 likes | 581 Views
COMP 7100: Computers in the Information society. MVC and Spring Framework Hongjun Song Computer Science The University of Memphis. MVC. Doug Engelbart: computer augmentation. What it is All About. ?. mental model. ?. data. ?. ?. Computer. use cases. operations. S. F.
E N D
COMP 7100: Computers in the Information society MVC and Spring Framework Hongjun SongComputer ScienceThe University of Memphis
Doug Engelbart: computer augmentation What it is All About ? mental model ? data ? ? Computer usecases operations
S F Scripting vs. Direct Manipulation • Out of main door • Turn right • 5th left • Right at 4th light • ½ left at 1st light • You’re there
User’s Mental ModelActivity Planning Network actA actC Code Algorithms DefineUseCases actD 2 weeks 3 weeks System Integration actB Define & CodeDomainClass attributes 2 weeks 7 weeks
GUI GUI bridgesgap between brain and data User – Machine Interaction usermental model data DomainData User
Controller 1 View 1 * 1 1 * View User work withModel seen throughView Controller creates and coordinates multiple Views Model – View - Controller usermental model data Model User Run Demo
Use Case exampleA Functional Requirement • Use Case # N: frontloading function • An activity is characterized by its duration, earlyStarttime, earlyFinish time,its predecessors and successors activities. • By default, earlyFinish = earlyStart + durationspecial activities may have more complex algorithms • An activity can start when all its predecessors are finished:earlyStart = MAX (earlyFinish all predecessors) Run Demo
COLLABORATION frontpreds [*] frontloader [1] INTERACTION frontpreds [*] frontloader [1] frontload() earlyFinish() frontloading – 1UML Diagrams • Critical Questions: • What are the roles? • How are they interconnected? • How do they interact? 1. What are the roles?2. How are they interconnected? 3. How do they interact?
The Essence of Object Orientation:Objects interact to achieve a given goal Critical questions: • What are the relevant objects? • The relevant objects are seen as a structure of Roles. • A role names the usage of one or more objects. • The name is seen as an alias for those objects. • How are they connected? • A Collaboration describes the structure of roles. • How do they interact? • An Algorithm specifies the interaction in terms of the roles.
Class and Role – 1Steven Pinker: How The Mind Works Classification: Group on common features (inst.vars. & methods) • Role (Artifact) : Group on common purpose • People categorize objects in terms of the roles they play within intuitive theories about how the world operates. • Roles are defined by what they can do and by what someone, somewhere, makes them to do at some time.
Class and Role – 2The TrumpeterHändel: Messiah, Hallelujah choir One Role - Two Classes
Role Playing in the TheatreHenrik Ibsen: Peer Gynt The Royal Hall of the King of the Dovre-Trolls. THE OLD MAN OF THE DOVRE sits on the throne, crowned, and with his sceptre in his hand. His CHILDREN and NEAREST RELATIONS are ranged on both sides. PEER GYNT stands before him. Violent commotion in the hall. ---------------- (THE GREEN-CLAD ONE) http://norsk.kameraklubb.net/coppermine/displayimage/album=167/pos=6.html
COLLABORATION frontpreds [*] frontloader [1] INTERACTION frontpreds [*] frontloader [1] frontload() earlyFinish() frontloading – 1UML Diagrams • Critical Questions: • What are the roles? • How are they interconnected? • How do they interact? 1. What are the roles?2. How are they interconnected? 3. How do they interact?
frontloading-2 Algorithm public void frontload (Integer startWeek) { FrontIntffrontloader = ??; Set<FrontpredIntf>frontpreds = ??; Integer earlyStart = startWeek; for (FrontpredIntf pred : frontpreds) { earlyStart = Math.max(earlyStart, pred.earlyFinish() + 1); } frontloader.setEarlyStart(earlyStart); }
What it still is All About mental model data GUI Model usecases operations
Model actC actA Activity name earlyStart earlyFinish duration color actD activities dependencies * * Dependency actB predecessor successor Data ModelConceptual Schema
Data ModelJava Domain Classes publicclass Model {public Set<Activity> activities= new HashSet<Activity>();public Set<Dependency> dependencies = new HashSet<Dependency>();…} publicclass Activityimplements FrontpredIntf, FrontIntf {private Integer earlyStart, earlyFinish, duration;private String name; …} publicclass Dependency {private Activitypredecessor, successor;…}
Interaction Algorithm Data Objects frontloader [1] frontpreds [*] actC actA frontload() mental model earlyFinish() data Collaboration Model actD frontloader [1] frontpreds [*] Query actB definefrontloaderas select act from activities act where act.earlyStart == nil and (for all pred in predecessors(act): pred.earlyStart != nil ) someInstance definefrontpredsas select dep.predecessor from dependencies dep where dep.successor = frontloader GUI usecases operations Roles and ObjectsBridging the gap with queries
frontloading-3 Algorithm public voidfrontload (Integer startWeek) { FrontIntffrontloader = ??; Set<FrontpredIntf>frontpreds = ??; Integer earlyStart = startWeek; for (FrontpredIntf pred : frontpreds) { earlyStart = Math.max(earlyStart, pred.earlyFinish() + 1); } frontloader.setEarlyStart(earlyStart); } FrontCollab frontCollab = new FrontCollab();FrontIntf frontloader = frontCollab.frontloader; Set<FrontpredIntf> frontpreds = frontCollab.frontpreds;
FrontCollabExternal Data View public classFrontCollab{public FrontIntf frontloader; public FrontpredIntf frontpreds;publicFrontCollab () {frontloader = selectFrontloader();frontpreds = predecessorsOf(frontloader);} }
Select domain object tofrontloader role by Java Query private FrontIntf selectFrontloader(){ for (Activity act : model.allActivities()) { if (act.earlyStart() == null) { Set<FrontpredIntf> predSet = predecessorsOf(act); if (areAllDone(predSet)) { frontloader = act; return(frontloader); } } } returnnull;
Select domain objects tofrontpreds role by Java Query public FrontpredIntf predecessorsOf(FrontIntf act){ Set<FrontpredIntf> preds = new HashSet<FrontpredIntf>(); for (Dependency assoc : model.dependencies() ) { if (assoc.successor() == act) { preds.add(assoc.predecessor()); } } return preds; }
Conclusion – 1 of 2: User NeedsBalance Thinking and Doing User needs are in two dimensions; they should be supported in harmony: thinking:→ mental model → data model → objects doing: → use case → collaboration → role → query → objects
realize instantiate Conclusion – 2 of 2: Architecture Balance State and Behavior Mental Model Use Cases Algorithm role interaction Conceptualschema reference roles Collaboration roles and links Classattributes select objects behavior state Data Objects
Reenskaug, T.: Original MVC notes from Xerox PARChttp://folk.uio.no/trygver/2007/MVC_Originals.pdf Reenskaug, T,: The BabyUML discipline of programming(where A Program = Data + Communication + Algorithms).SoSym 5,1 (April 2006). DOI: 10.1007/s10270-006-0008-x.http://heim.ifi.uio.no/~trygver/2006/SoSyM/trygveDiscipline.pdf Reenskaug, T.: Programming with Roles and Classes; the BabyUML ApproachTo be published by Nova publishers as a chapter in a book on Computer Software Engineering Research [WEB PAGE] http://folk.uio.no/trygver/2007/babyUML.pdf (.PDF)) Unified Modeling Language: Superstructure. Version 2.1.Object Management Group (OMG) document ptc/06-04-02. http://www.omg.org Arisholm, E.; Sjøberg, D.:A Controlled Experiment with Professionals to Evaluate the Effect of a Delegated versus Centralized Control …,Simula Research Laboratory Technical Report 2003-6http://www.simula.no/publication_one.php?publication_id=601 Reenskaug, T; Wold, P.;, Lehne, O. A.: Working With Objects. This book is out of print. An early .pdf version kan be downloaded free from http://folk.uio.no/trygver/1996/book/book11d.pdf Wirfs-Brock, R.; McKean, A.; Object Design. Roles, Responsibilities, and Collaborations.ISBN 0‑201‑37943‑0; Addison-Wesley; Boston, MA, 2003. Andersen, E. P.; Conceptual Modeling of Objects. A Role Modeling Approach.D.Scient thesis, November 1997, University of Oslo. [web page] http://heim.ifi.uio.no/~trygver/1997/ EgilAndersen/ConceptualModelingOO.pdf Pinker, S.; How the Mind Works; ISBN 0-393-04535-8; Norton; New York, NY, 1997. More reading
What is the Spring Framework? • Spring is a Lightweight Application Framework • Where Struts, WebWork and others can be considered Web frameworks, Spring addresses all tiers of an application • Spring provides the plumbing so that you don’t have to!
Spring Framework History • Started 2002/2003 by Rod Johnson and Juergen Holler • Started as a framework developed around Rod Johnson’s book Expert One-on-One J2EE Design and Development • Spring 1.0 Released March 2004 • 2004/2005 Spring is emerging as a leading full-stack Java/J2EE application framework
Spring == J2EE Application Server? • Spring is NOT a J2EE application server • Spring can integrate nicely with J2EE application servers (or any Java environment) • Spring can, in many cases, elegantly replace services traditionally provided by J2EE application servers
Lessons Learned from Struts • Before Struts, everyone wrote their own front controllers (or YIKES! put their controller logic in JSP) • After Struts, the custom front controllers could be thrown out • Developers focus on solving business problems • Productivity Gain! • But with Struts (and most of the other web frameworks) you still have to write your own business delegates or service layers…
Spring Can Help! • Spring brings a consistent structure to your entire application • Spring provides a consistent way to glue your whole application together • Spring provides elegant integration points with standard and defacto-standard interfaces: Hibernate, JDO, TopLink, EJB, RMI, JNDI, JMS, Web Services, Struts, etc. • Just as Struts did on the web tier, we can realize huge productivity gains by not having to write the common integration points across your application
The Spring Framework Mission Statement From springframework.org The authors of Spring believe that: • J2EE should be easier to use • It's best to program to interfaces, rather than classes. Spring reduces the complexity cost of using interfaces to zero. • JavaBeans offer a great way of configuring applications. • OO design is more important than any implementation technology, such as J2EE. • Checked exceptions are overused in Java. A framework shouldn't force you to catch exceptions you're unlikely to be able to recover from. • Testability is essential, and a framework such as Spring should help make your code easier to test.
Spring Framework Mission Statement (continued) The authors of Spring aim that: • Spring should be a pleasure to use • Your application code should not depend on Spring APIs • Spring should not compete with good existing solutions, but should foster integration. (For example, JDO and Hibernate are great O/R mapping solutions. We don't need to develop another one.)
Spring Overview from springframework.org Note: Spring distribution comes as one big jar file and alternatively as a series of smaller jars broken out along the above lines (so you can include only what you need)
Spring is Non-Invasive What does that mean? • You are not forced to import or extend any Spring APIs • An invasive API takes over your code. • Anti-patterns: • EJB forces you to use JNDI • Struts forces you to extend Action Invasive frameworks are inherently difficult to test. You have to stub the runtime that is supplied by the application server
But really, whatISSpring? At it’s core, Spring provides: • An Inversion of Control Container • Also known as Dependency Injection (Fowler’s term) • An AOP Framework • Spring provides a proxy-based AOP framework • You can alternatively integrate with AspectJ or AspectWerkz • A Service Abstraction Layer • Consistent integration with various standard and 3rd party APIs These together enable you to write powerful, scalable applications using POJOs.
Seriously though, whatISSpring? • Spring at it’s core, is a framework for wiring up your entire application • BeanFactories are the heart of Spring
BeanFactories • A BeanFactory is typically configured in an XML file with the root element: <beans> • The XML contains one or more <bean> elements • id (or name) attribute to identify the bean • class attribute to specify the fully qualified class
BeanFactories • By default, beans are treated as singletons • Can also be prototypes Here is an example: The bean’s fully- qualified classname The bean’s ID <beans> <bean id=“widgetService” class=“com.zabada.base.WidgetService”> <property name=“poolSize”> <!—-property value here--> </property> </bean> </beans> Maps to a setPoolSize() call
Property Values for BeanFactories • Strings and Numbers • Arrays and Collections <property name=“size”><value>42</value></property> <property name=“name”><value>Jim</value></property> <property name=“hobbies”> <list> <value>Basket Weaving</value> <value>Break Dancing</value> </list> </property>
Property Values for BeanFactories (continued) The real magic comes in when you can set a property on a bean that refers to another bean in the configuration: This is the basic concept of Inversion of Control <bean name=“widgetService” class=“com.zabada.base.WidgetServiceImpl”> <property name=“widgetDAO”> <ref bean=“myWidgetDAO”/> </property> </bean> calls setWidgetDAO(myWidgetDAO) where myWidgetDAO is another bean defined in the configuration
Dependency Injection(Inversion of Control) • Complicated sounding terms for a fairly simple concept • The “Hollywood Principle”: Don’t call me, I’ll call you • Dependencies used from within a bean aren’t asked for outwardly, but are injected into the bean by the container
Dependency Injection(Inversion of Control) • Eliminates lookup code from within your application • Allows for pluggablity and hot swapping • Promotes good OO design • Enables reuse of existing code • Makes your application extremely testable
A Very Special BeanFactory:the ApplicationContext • An ApplicationContext is a BeanFactory, but adds “framework” features such as: • i18n messages • Event notifications • This is what you will probably most often use in your Spring applications
AOP (Aspect-Oriented Programming) • AOP decomposes a system into concerns, instead of objects. • Deals with "aspects" that cross-cut across the code and can be difficult or impossible to modularize with OOP • The most common example given is logging • Code for doing logging typically must be scattered all over a system • With AOP, you can declare, for example, that a system should write a log record at the beginning and end of all method invocations.
AOP (Aspect-Oriented Programming) AOP enables the delivery of services to POJOs • Spring provides pre-packaged AOP services: • Declarative Transaction Management • Security • Logging • You can write custom AOP services for: • Auditing • Caching • Custom security
Service Abstraction Layers Spring provides abstraction for: • Transaction Management • JTA, JDBC, others • Data Access • JDBC, Hibernate, JDO, TopLink, iBatis • Email • Remoting • EJB, Web Services, RMI, Hessian/Burlap
Service Abstraction Layers Benefits: • No implicit contracts with JNDI, etc. • Insulates you from the underlying APIs • Greater reusability • Spring abstractions always consist of interfaces • This makes testing simpler • For data access, Spring uses a generic transaction infrastructure and DAO exception hierarchy that is common across all supported platforms