Download presentation
Presentation is loading. Please wait.
1
JAVA Design Patterns
2
Interfaces Interfaces define a contract
Contain methods and their signatures Can also include static final constants (and comments) But no implementation Very similar to abstract classes One interface can extend another, but An interface cannot extend a class A class cannot extend an interface Classes implement an interface
3
Defining Interfaces Use the interface keyword
public interface Vehicle { public void turnLeft(); public void turnRight(); } Like abstract methods, the signature is terminated with a semi-colon
4
Implementing Interfaces
Use the implements keyword public class MotorBike implements Vehicle { //include methods from Vehicle interface } Class must implement all methods of the interface OR declare itself to be abstract Classes can implement any number of interfaces public class MotorBike implements Vehicle, Motorised Possible to combine extends and implements public class MotorBike extends WheeledVehicle implements Vehicle, Motorised
5
Sapana Mehta (CS-6V81) Design Patterns A pattern is a proven solution to a problem in a context. Christopher Alexander says each pattern is a three-part rule which expresses a relation between a certain context, a problem, and a solution. Design patterns represent a solutions to problems that arise when developing software within a particular context.
6
Categorizing Pattern Design Architectural Analysis Creational
Patterns, then, represent expert solutions to recurring problems in a context and thus have been captured at many levels of abstraction and in numerous domains. Numerous categories are: Design Architectural Analysis Creational Structural Behavioral
7
Sun’s J2EE Framework Components Containers and Connectors: Hiding Complexity, Enhancing Portability Components are the key focus of application developers Containers intercede between clients and components, providing services transparently to both, including transaction support and resource pooling. Connectors sit beneath the J2EE platform, defining a portable service API to plug into existing enterprise vendor offerings.
9
J2EE and Design Patterns
J2EE: AN OPERATING SYSTEM FOR THE WEB Enterprise web applications, which live on networks and are accessible through browsers, are redefining Enterprise Web Software. This is the next wave of computing. The J2EE architecture is built to enable component developers Design Pattern.
10
Java Pet Store- MVC Design Pattern
The Java Pet Store is a reference application that demonstrates J2EE technologies. The Pet Store application implements MVC (Model-View-Controller) design, and demonstrates one way to design an application that should scale well.
11
ShoppingCart.jsp Java Server Pages (JSP)
12
Elements of Design Patterns
Design patterns have 4 essential elements: Pattern name: increases vocabulary of designers Problem: intent, context, when to apply Solution: UML-like structure, abstract code Consequences: results and tradeoffs
13
Abstract Factory
14
Abstract Factory Provide an interface for creating families of related or dependent objects without specifying their concrete classes. The real-world example demonstrates the creation of different animal worlds for a computer game using different factories. Although the animals created by the Continent factories are different, the interactions among the animals remain the same.
15
Abstract Factory
17
Abstract Factory: Participants
AbstractFactory Declares an interface for operations that create abstract products ConcreteFactory Implements the operations to create concrete product objects: usually instantiated as a Singleton AbstractProduct Declares an interface for a type of product object; Concrete Factories produce the concrete products ConcreteProduct Defines a product object to be created by the corresponding concrete factory
19
abstract class AbstractProductA{ public abstract void operationA1(); public abstract void operationA2(); } class ProductA1 extends AbstractProductA{ ProductA1(String arg){ System.out.println("Hello "+arg); } // Implement the code here public void operationA1() { }; public void operationA2() { };
20
class ProductA2 extends AbstractProductA{ ProductA2(String arg){ System.out.println("Hello "+arg); } // Implement the code here public void operationA1() { }; public void operationA2() { }; }
21
abstract class AbstractProductB{ //public abstract void operationB1(); //public abstract void operationB2(); } class ProductB1 extends AbstractProductB{ ProductB1(String arg){ System.out.println("Hello "+arg); } // Implement the code here
22
class ProductB2 extends AbstractProductB{ ProductB2(String arg){ System.out.println("Hello "+arg); } // Implement the code here }
23
abstract class AbstractFactory{ abstract AbstractProductA createProductA(); abstract AbstractProductB createProductB(); } class ConcreteFactory1 extends AbstractFactory{ AbstractProductA createProductA(){ return new ProductA1("ProductA1"); AbstractProductB createProductB(){ return new ProductB1("ProductB1");
24
class ConcreteFactory2 extends AbstractFactory{ AbstractProductA createProductA(){ return new ProductA2("ProductA2"); } AbstractProductB createProductB(){ return new ProductB2("ProductB2");
25
//Factory creator - an indirect way of instantiating the factories class FactoryMaker{ private static AbstractFactory pf=null; static AbstractFactory getFactory(String choice){ if(choice.equals("a")){ pf=new ConcreteFactory1(); }else if(choice.equals("b")){ pf=new ConcreteFactory2(); } return pf; }
26
// Client public class Client{ public static void main(String args[]){ AbstractFactory pf=FactoryMaker.getFactory("a"); AbstractProductA product=pf.createProductA(); //more function calls on product }
27
Consequences 1. Concrete class isolation (Good) Client does not interact with the implementation classes Client only manipulates instances through the abstract interfaces
28
Consequences 2. Product families easily exchanged (Good)
Only have to change the concrete factory Can be done at run time
29
Consequences 3. Products are more consistent (Good)
Helps the products in each product family consistently be applied together (assuming they work well together) Only one family at a time
30
Consequences 4. Difficult to support new kinds of products (Bad)
Extending existing abstract factories to make new products is difficult and time consuming The family of products available is fixed by Abstract Factory interface
32
Singleton
33
Singleton Do we need to limit the no of objects of a class
35
Singleton Intent: Ensure that a class only has one instance, and provide a global point of access to it Applicability: There must be exactly one instance of a class, and it must be accessible to clients from a well-known access point When the sole instance should be extensible by subclassing, and clients should be able to use an extended instance without modifying their code
36
Singleton
37
Singleton Pattern Problem Context Solution core
Want to ensure a single instance of a class, that’s shared by all uses throughout a program (e.g., the Portfolio) Context Need to address initialization versus usage ordering Solution core Provide a global access method (static member function) First use of the access method instantiates the class
38
Singleton Pattern Solution core Consequences
Constructors for instance can be hidden (made private) Can hide destructor too if a “fini” method is also provided Consequences Object is never created if it’s never used Object is shared efficiently among all uses
39
Observer pattern Intent: Used in Model-View-Controller framework
Define a one-to-many dependency between objects so that when one object changes state, all its dependents are notified and updated automatically Used in Model-View-Controller framework Model is problem domain View is windowing system Controller is mouse/keyboard control How can Observer pattern be used in other applications? JDK’s Abstract Window Toolkit (listeners) Java’s Thread monitors, notify(), etc.
40
Structure of Observer Pattern
41
Creational Patterns Abstract Factory: Builder: Factory Method:
Factory for building related objects Builder: Factory for building complex objects incrementally Factory Method: Method in a derived class creates associates Prototype: Factory for cloning new instances from a prototype Singleton: Factory for a singular (sole) instance
42
Adapter Pattern Problem
Have an object with an interface that’s close to (but is not exactly) what we need Context Want to re-use an existing class Can’t change its interface It’s impractical to extend class hierarchy more generally Solution Core Wrap a particular class or object with the interface needed (2 forms: class form and object forms)
43
Adapter «Adaptee» «Superclass» «Adapter» adaptedMethod
polymorphicMethod «Adapter» polymorphicMethod() return adaptee.adaptedMethod(); { }
44
Adapter Structure (Class Form)
Interface Impl method () = 0; impl_method (); public private Adapter method () { impl_method (); }; Interface abstract base class provides desired interface Impl concrete class provides the implementation Adapter glues them together via inheritance
45
Adapter Structure (Object Form)
Interface method () = 0; impl_ Adapter Impl method () { impl_->impl_method(); }; impl_method (); Interface abstract base class provides desired interface Impl concrete class provides the implementation Adapter glues them together via delegation
46
Adapter Example TimsTorus ThreeDShape Sphere Torus volume() { return
calcVolume ThreeDShape volume Sphere Torus volume() return adaptee.calcVolume(); { }
47
objects whose state can be watched
Pattern: Observer objects whose state can be watched
48
Observer Intent Define a one-to-many dependency between objects so that when one object changes state, all its dependents are notified and updated automatically. The object that changes state is called the subject and the other objects are the observers.
49
Observer design pattern
In many programs, when object changes state, other objects may have to be notified Example: when a car in a game is moved The graphics engine needs to know to re-render item The traffic computation routines need to re-compute the traffic pattern Another example: data in a spreadsheet The display must be updated Possibly multiple graphs that use that data need to re-draw themselves This pattern answers the question: How best to notify those objects when the subject changes?
50
Motivation Separate presentation aspects of the UI from the underlying application data. e.g., spreadsheet view and bar chart view don't know about each other they act as if they do: changing one changes the other.
51
Observer: Structure
52
Observer pattern The key participants in this pattern are:
The Subject, which provides an (virtual) interface for attaching and detaching observers The Observer, which defines the (virtual) updating interface The ConcreteSubject, which is the class that inherits/extends/implements the Subject The ConcreteObserver, which is the class that inherits/extends/implements the Observer
Similar presentations
© 2024 SlidePlayer.com. Inc.
All rights reserved.