You are on page 1of 132

Modular Software Design

ALLAHBAKSH ASADULLAH

Agenda
1.

Why Modular Software, Effect of the different Architecture style

2.

Design Pattern for common software systems

3.

Design Pattern for Multilayer Applications

4.

Plugins for Extensible Software Systems

5.

REST based Architecture Style

6.

Micro-service Architecture

7.

Architecture of Large Software System in Enterprise

Rules of class .

Have you seen this site .

We will see more of this .

Lets see something more .

What is your Observation .

Meru Mobile App Login OBSERVATIONS .

Book a Cab .

Menu OBSERVATIONS Menu should be pluggable Focus Essential It should extensible (add new menu) Ease of use .

Check your Booking OBSERVATIONS .

Feedback OBSERVATIONS .

Fares OBSERVATIONS .

Profile OBSERVATIONS .

Some more things to Observe .

Some more things… .

Lets see a broader Picture .

Now we have to see how .

Load Balan cer HIGH LEVEL API A view of the Architecture REST based Web Service REST based Web Service REST based Web Service REST based Web Service Payment Gateways C a c h e Data base .

interchangeable modules. .Module? Module is a set of standardized parts or independent units that can be used to construct a more complex structure. such as an item of furniture or a building. Modular programming is a software design technique that emphasizes separating the functionality of a program into independent. such that each contains everything necessary to execute only one aspect of the desired functionality.

Net world? What are Layers? Can modules exchange data? .Can we define good program What should be idle size of a class? Whether Java has module system? How many methods a class should have ideally? Is Jar a module? ◦ How many should be public how many should be private? ◦ Should we have static methods? Should I use interface or abstract class? ◦ Is there any difference between abstract class and interface? If yes then what? What do you mean by Package? What is equivalent of it in .

List Down Advantages of Modular Program? .

It is defined by the W3C's XML 1.0 Specification JavaScript Object Notation. is an open standard format that uses human-readable text to transmit data objects consisting of attribute–value pairs. largely replacing XML.What is common format for data exchange? XML JSON Extensible Markup Language (XML) is a markup language that defines a set of rules for encoding documents in a format which is both human-readable and machine-readable. . It is the primary data format used for asynchronous browser/server communication (AJAX).

.

OO Design Pattern .

Object Oriented (OO) Basics Abstraction Encapsulation Inheritance Polymorphism .

OO Principles Encapsulate what varies Favor Composition over Inheritance Program to Interface not implementation Inheritance Strive for loose coupled design between Object and interaction Classes should be Open for Extension but closed for modification .

Introduction to Design Patterns Creational Patterns • Decouple client from the Objects creation it needs to instantiate Structural Patterns • Ease the design by identifying a simple way to realize relationships between entities Behavioral Patterns • Identify common communication patterns between objects and realize these patterns. . these patterns increase flexibility in carrying out this communication. By doing so.

Creational Patterns .

Private constructor to restrict instantiation of the class from other classes. it comes with a lot of implementation concerns. Private static variable of the same class that is the only object of the class. .Singleton Singleton pattern restricts the instantiation of a class and ensures that only one object of the class exists in the JVM. It seems to be a very simple design pattern but when it comes to implementation.

It seems to be a very simple design pattern but when it comes to implementation.Singleton Singleton pattern restricts the instantiation of a class and ensures that only one object of the class exists in the JVM. Public static method that returns the object of the class. Different approaches of Singleton pattern implementation and design concerns with the implementation . it comes with a lot of implementation concerns. this is the global access point for outer world to get the object of the singleton class.

Different Approach of Singleton Eager initialization Static block initialization Lazy Initialization Thread Safe Singleton Using Reflection to destroy Singleton Pattern Enum Singleton .

It doesn’t provide option for Exception handling. . Use only when Singleton class is not using a lot of resources. Eager initialization: Object of Singleton Class is created at the time of class loading. Easiest method to create a singleton It has a drawback that object is created even though client application might not be using it.Singleton Pattern Contd..

◦ This makes it able to handle exception.Singleton with Static Init Static block initialization is similar to eager initialization the only difference is that object of class is created in the static block. Creates the Object of class even if it is not used .

Singleton .

Enum as Singleton This is used now widely Has both advantage and disadvantages .

MS Excel creates spreadsheets . It is also know as Virtual Constructor Factory Method use abstract classes to define and maintain relationships between objects Framework has to create objects as well .moves this knowledge out of the framework Example: Generalizing the relationship between an application and the documents it processes Generalization: Application creates Documents Concretized by: MS Paint creates Gifs. MS Word creates Word Documents.which it cannot instantiate Factory method encapsulates knowledge of which subclass to create .must instantiate classes but only knows about abstract classes .Factory Method Encapsulate Object Creation.

Motif. PM Abstract class for widget. supporting class for specific platform widget . e.g. and other data structures Want users to not know or care how these structures are implemented (separation) Example: UI toolkit to support multiple look-and-feel standards. Queues.Abstract Factory Provide an interface for creating objects without specifying their concrete classes Example: Stacks..

package org.iiitj.abstractfactory. } public interface GUIFactory { Button createButton().iiitj. } . Label createLabel().package org. } package org.iiitj. public interface Label { void paint(). public interface Button { void paint().abstractfactory.abstractfactory.

//new OSXFactory(). package org. else return null.getProperty("os. } public class WinFactory implements GUIFactory { public void applicaiton(GUIFactory factory){ Button button = factory.createButton(). public class Main { public static void main(String[] args) { new Main(). if(osname != null && osname.name"). } @Override public Label createLabel() { // TODO Auto-generated method stub return null.iiitj.iiitj. } } @Override public Button createButton() { // TODO Auto-generated method stub return null. } } .applicaiton(createOsSpecificFactory()).package org.toLowerCase(). } public static GUIFactory createOsSpecificFactory() { String osname = System.abstractfactory.abstractfactory.contains("windows")) return new WinFactory().

Composite(Objects that can serve as containers) An object that is either an individual item or a collection of many items A composite objects can be composed of individual items or of other composites In short Object which can hold themselves Often leads to a tree structure of leaves and nodes Examples in Java: ◦ Collections (a List of Lists. etc. a set of Sets) ◦ GUI layout (panels containing panels containing buttons.) 42 .

. delegate to a default constructor. that receives each initialization parameter step by step and then returns the resulting constructed object at once. In this pattern. the builder pattern uses another object. It avoids telescoping of constructor. your POJO has numerous constructors each taking a different number of parameters that. a builder.Builder Pattern The builder pattern is an object creation software design pattern. The Telescoping Constructor is an example of a pattern that borders on an anti-pattern that is all too often used in projects even though there are better alternatives availble. Instead of using numerous constructors. if the class has been written correctly. The intention of the builder pattern is to find a solution to the telescoping constructor antipattern.

Builder Pattern 1. After setting all the argument call the build method or create method. 4. Create a Builder Class 2. 3. Each method in the Builder class will take and arguments or set of argument and return object of the Builder class. It returns Object of class for which Builder was created .

clone(). and create new objects by copying this prototype ◦ When product creation should be decoupled from system behavior ◦ When to avoid subclasses of an object creator in the client application ◦ When creating an instance of a class is time-consum Allows specifying new objects by varying values or structure It is built on the method . .Prototype Specify the kinds of objects to create using a prototypical instance. Moreover. classes that have circular references to other classes cannot really be cloned. which could be complicated sometimes in terms of shallow copy and deep copy.

clone(). } public void setFloat(float inSize) { size = inSize.clone(). } } .public class DVD implements Prototype{ private String name. } public void setName(String name) { this. public String getName() { return name. } public Prototype clone() throws CloneNotSupportedException { return (DVD)super. private float size.name = name. } public float getSize() { return size. } } public class CD implements Prototype { private String name = null.name = name. } @Override public Prototype clone() throws CloneNotSupportedException { // TODO Auto-generated method stub return (CD)super. public String getName() { return name. } public void setName(String name) { this.

Structural Patterns .

General Manager The intent of a composite is to "compose" objects into tree structures to represent partwhole hierarchies. Implementing the composite pattern lets clients treat individual objects and compositions uniformly. Manager Developer Developer Developer 48 .Composite pattern The composite pattern describes that a group of objects is to be treated in the same way as a single instance of an object.

Lets see how do we do it public interface Employee { public void add(Employee employee). public void print(). public void remove(Employee employee). public double getSalary(). public String getName(). } . public Employee getChild(int i).

such as a class library. since the facade has convenient methods for common tasks. thus allowing more flexibility in developing the system. ◦ Make the library more readable ◦ Reduce dependencies of outside code on the inner workings of a library. ◦ Wrap a poorly designed collection of APIs with a single well-designed API. since most code uses the facade. understand and test. .Facade A facade is an object that provides a simplified interface to a larger body of code. A facade can: ◦ Make a software library easier to use.

iiitj. } public void jump(long memoryPosition){ } } } public void execute(){ } } . processor. hd = new HardDrive(). package org. ram = new Memory().freeze().execute().iiitj. public class CPU { public void freeze(){ public ComputerFacade() { processor = new CPU(). private HardDrive hd. } public void doSomeWork() { processor. processor. private Memory ram.freeze().package org. hd.jump(BOOT_ADDRESS). public class ComputerFacade { private CPU processor.facade. SECTOR_SIZE)). ram.load(BOOT_ADDRESS. processor.facade.read(BOOT_SECTOR.

facade. package org.iiitj. int size){ some implementation here and return here null. byte[] data) { } } . public class Memory { public void load(long position.iiitj. public public //TODO object return } } class HardDrive { byte[] read(long location.facade.package org.

Decorator Pattern ( ) objects that wrap around other objects to add useful features 53 .

scroll bars and borders to GUI controls 54 . or adds features to.Decorator Pattern Decorator: an object that modifies behavior of. another object ◦ Decorator must maintain the common interface of the object it wraps up used so that we can add features to an existing simple object without needing to disrupt the interface that client code expects when using the simple object Examples in Java: ◦ multilayered input streams adding useful I/O methods ◦ adding designs.

Decorator example: I/O Normal InputStream class has only public int read() method to read one letter at a time Decorators such as BufferedReader or Scanner add additional functionality to read the stream more easily 55 .

.Flyweight Pattern A flyweight is an object that minimizes memory use by sharing as much data as possible with other similar objects. and it is common practice to hold them in external data structures and pass them to the flyweight objects temporarily when they are used. it is a way to use objects in large numbers when a simple repeated representation would use an unacceptable amount of memory. Often some parts of the object state can be shared.

put(flavorName. } import java. float price) { if (!flavours. package org. return flavours.name = name.Map. CoffeeFlavour> flavours = new HashMap<String.iiitj.HashMap. } int totalCoffeeFlavoursMade() { return flavours.size(). this. } } public class Menu { private Map<String.package org.util. CoffeeFlavour lookup(String flavorName. } public float getPrice() { return price.containsKey(flavorName)) flavours. public String getName() { return name. CoffeeFlavour>().flyweight.iiitj. } public CoffeeFlavour(String name) { super(). new CoffeeFlavour(flavorName)).util.flyweight. public void setPrice(float inPrice){ price= inPrice. public class CoffeeFlavour { private final String name. } } .get(flavorName). import java. private float price.

Behavioral Patterns .

Iterator pattern Iterator an object that provides a standard way to examine all elements of any collection Uniform interface for traversing many different data structures without exposing their implementations (java.util.Iterator<E>) Supports concurrent iteration and element removal Removes need to know about internal structure of collection or different methods to access data from different collections 59 .

In contrast.External Iterator vs Internal Iterator Clients that use an external iterator must advance the traversal and request the next element explicitly from the iterator. . External iterators are more flexible than internal iterators. the client hands an internal iterator an operation to perform. It's easy to compare two collections for equality with an external iterator. because the iterator implementation doesn't have to explicitly store and manage the state of the iteration. Iteration using internal iterators is often much easier to implement. and the iterator applies that operation to every element in the aggregate.

private int elementIndex. } @Override public boolean hasNext() { try{ Employee employee = list. } @Override public Employee next() { Employee employee = list. public EmployeeIterator(List<Employee> inList) { list = inList. } return true. }catch(Exception e){ return false. public class Employee { } public class EmployeeIterator implements Iterator<Employee> { private List<Employee> list. return employee. } .get(elementIndex).iiitj.iterators. elementIndex++.package org.get(elementIndex).

Template Pattern
•Defines a program skeleton of an algorithm in a.
a method, called template method, which
defers some steps to subclasses.
b.
•Redefine certain steps of an algorithm without
changing the algorithm's structure

Define an abstract class with steps of each
algorithm as method

c.

You can not change the order of the
implementation is called

The order in which each step has to be
executed is put in the final method of
abstract class.

The Observer Pattern

The Weather Monitoring Example
The Weather Monitoring application

The Weather Monitoring Example Task ◦ We need to implement measurementsChanged so that it updates three different displays for current conditions. and forcasts ◦ measurementsChanged is called any time data changes. weather stats. we don’t know or care how this method is called ◦ Three display types must be updated ◦ The system must be expandable – new display types will be added .

Observer Sometimes called publish/subscribe ◦ Similar to call-back handlers ◦ One-to-Many relationship Benefits ◦ Listening object gets information when needed ◦ Subject does not become dependent on multiple observers .

the can interact but they have very little knowledge of each other The Observer Pattern loosley coupled design ◦ ◦ ◦ ◦ The only thing the subject knows about observer is that it implements a certain interface We can add new observers at any time We never need to modify the subject to add new types of observers We can reuse subjects or observers independent of each other .Loose Coupling When two object are loosley coupled.

Pattern: Strategy objects that hold alternate algorithms to solve a problem 68 .

one implementation of how to solve the same problem ◦ how is this different from Command pattern? separates algorithm for behavior from object that wants to act allows changing an object's behavior dynamically without extending / changing the object itself examples: ◦ file saving/compression ◦ layout managers on GUI containers ◦ AI algorithms for computer game players 69 .Strategy pattern pulling an algorithm out from the object that contains it. and encapsulating the algorithm (the "strategy") as an object each strategy implements one behavior.

setStrategy(new SmartStrategy()). // using a strategy Card p1move = player1. } // setting a strategy player1.Strategy example: Card player // Strategy hierarchy parent // (an interface or abstract class) public interface Strategy { public Card getMove().move(). 70 // uses strategy .

REST Web Services ALLAHBAKSH ASADULLAH .

and/or delete a web resource. .Introduction to REST Representational ◦ Clients possess the information necessary to identify. Transfer ◦ Client state is passed from the client to the service through HTTP. State ◦ All resource state information is stored on the client. modify.

Uniform interface 2. . Stateless 4. Extensible through code on demand (optional) * Services that do not conform to the above required constraints are not strictly RESTful web services. Cacheable 5.Introduction to REST The six characteristics of REST: 1. Layered 6. Decoupled client-server interaction 3.

form parameters. ◦ Specifies the verb.HTTP-REST Request Basics The HTTP request is sent from the client. or HTTP method to use when accessing the resource. ◦ Identifies the location of a resource. ◦ Supplies an optional request body that identifies additional data to be uploaded to the server (e.g. ◦ Supplies optional request headers (name-value pairs) that provide additional information the server may need when processing the request. attachments. etc.) .

g.1 User-Agent: IE Request Headers Content-Type: application/x-www-form-urlencoded [CRLF] name=x&id=2 Request Body (e. form parameters) .1 User-Agent: Chrome Accept: application/json [CRLF] Requested Resource (path and query string) Request Headers (no request body) A typical client POST request: Requested Resource (typically no query string) POST /save HTTP/1.HTTP-REST Request Basics Sample Client Requests: A typical client GET request: GET /view?id=1 HTTP/1.

◦ Supplies an optional response body that identifies additional data to be downloaded to the client (html. binary data. ◦ Supplies response headers (name-value pairs) that provide additional information about the response. etc.) .HTTP-REST Response Basics The HTTP response is sent from the server. ◦ Gives the status of the processed request. xml.

1 500 Internal Server Error Response Status HTTP/1.HTTP-REST Response Basics Sample Server Responses: Response Status HTTP/1.Some HTML Content.1 201 Created Location: /view/7 Response Header [CRLF] Response Body Some message goes here. Response Status .1 200 OK Content-Type: text/html Response Headers Content-Length: 1337 [CRLF] <html> <!-. --> Response Body (content) </html> HTTP/1.

PUT – Add a new resource at the request URL DELETE – Removes the resource at the request URL OPTIONS – Indicates which methods are supported HEAD – Returns meta information about the request URL . POST – Submits information to the service for processing ◦ Should typically return the new or modified resource. as it will be discarded. but should not modify on it. ◦ May be cached locally or on the server. ◦ May produce a resource.HTTP-REST Vocabulary HTTP Methods supported by REST: GET – Requests a resource at the request URL ◦ Should not contain a request body.

The path and query string can be used to identify and customize the accessed resource.HTTP-REST Vocabulary A typical HTTP REST URL http://<WebSiteName>/location/list?category=prof&limit=20 protocol host name path to a resource query string The protocol identifies the transport scheme that will be used to process and respond to the request. . The host name identifies the server address of the resource.

POST) Supplied path information (e. and path parameters Headers. etc. cookies.g /service/listItems) Query. .g. GET. form.HTTP and REST A REST service framework provides a controller for routing HTTP requests to a request handler according to: The HTTP method used (e.

◦ Typically integrates with other technologies. . ◦ Eliminates the need to write “boilerplate” code. such as Spring. Using a REST service framework.Producing REST Services REST services in Java web applications can be implemented in several ways: As a plain Java Servlet ◦ Adequate for very simple REST services. Java provides the JAX-RS specification for use by providers of REST service frameworks. ◦ Requires a lot of “boiler plate” code for complex services.

REST on the Java Stack Although developers may implement REST web services however they choose. the Java Stack team is best equipped to support the following: Jersey A JAX-RS web service framework Apache CXF ◦ A JAX-RS web service framework Spring MVC ◦ An MVC framework built upon the Spring Platform (does not implement the JAX-RS specification) .

create a new faculty / faculty /{faculty-id} ◦ GET .get a faculty details ◦ DELETE.calculate average marks of students /faculty ◦ GET .get an student representation ◦ PUT .submit a new order /students/{studentId} ◦ GET .update an student info ◦ DELETE – delete a student info /student/average-marks ◦ GET .remove a faculty details / faculty /{facutly-id}/courses ◦ GET .list all faculty ◦ POST .Designing services with a Uniform Interface /students ◦ GET .list all students ◦ POST .get the courses offered by a faculty .

@PUT. @POST. @HEADER ◦ Identifies which HTTP method the Java method is interested in .JAX-RS Annotations @Path ◦ Defines URI mappings and templates @Produces. @Consumes ◦ What MIME types does the resource produce and consume @GET. @DELETE.

Architecture Style
HTTP GET

Response
(XML doc)

Request
(XML doc)

HTTP Response

HTTP POST

Response
(JSON doc)

PO
(XML doc)

Response
(TEXT doc)

URL 1

URL 1
HTTP Response

HTTP DELETE

doGet()

Web/Proxy Server

Request
(XML doc)

doPost(id)

REST Engine
(locate resource
and generate
response)

doDelete()

URL 1
HTTP Response

85

A Layered Diagram of Big Data
Platform(Exampleof Layers)
Hypertable

Hbase

Zoo Keeper

Ambari

Pig

Hive

Mahout

Hadoop Map Reduce

Pig

Hive

Tez

Mahout

Shark

Impala

YARN

HDFS 2

Giraph

GraphX

Spark

MLib

Open
MPI

Sazma

Building Extensible Applications

Few Examples: 1) Eclipse 2) Chrome 3) Firefox 4) Gimp 5)…. extending the application is know as extensible application. .Extensible Application Definition Without modifying the core application.

What is an Extensible Application* Just by adding the new JAR onto the application class path or into the application specific extension directory. and perhaps even customers to add service providers without modifying the original application. vendors. we can add new functionalities or APIs to the application. *In our context . An application with extensible services will allow us.

Creating an Example Application Airport Provide Cab Services The Airport Software is need to print the receipt based on type of Cab and Service Provider. New Cab Provider register themselves with Airport Airport Software need modification? . KM etc.

Does Java Provide Framework? YES ServiceLoader is class in JDK6 (Prior it was not public ) ServiceLoader looks in the Classpath and loads the plugin Requires specific format of Jar .

Airport Car Service Airport provides a ICab interface to be implemented public interface ICab{ public int getBaseFare(). public int getPrice(float km). public String getCarVendor(). } The service provider like MeruCab should implement this and package their class in Jar file .

Put one classname on one line.cab.bial.ICab Put this jar in the classpath.cab.jar * ◦ The Jar includes com.Some Config or Module Files Create a file in META-INF/services/com.ICab ◦ The file content will be the classes which implements ICab within that jar. Write your simple loading mechanism using ServiceLoader .bial. ◦ Comment prefixed by # Create a Jar file with MeruCab ◦ jar –cf merucab.

load(ICab. while (cabIterator. // Do something with Cab objects } .Driver to Drive the Cab… ServiceLoader<ICab>loader = ServiceLoader.class).hasNext()) { ICab car = carIterator.next(). Iterator<ICab> cabIterator = loader.iterator().

and objects in the current Java™ virtual machine.Java Reflection “Reflection in a programming language context refers to the ability to observe and/or manipulate the inner workings of the environment programmatically.” “The reflection API represents. interfaces. .” It consists of metadata plus operations to manipulate the metadata. the classes. or reflects.

lang.Metadata a Bird Eye View Metadata classes in Java java.lang.reflect.reflect.Method .Field java.lang.lang.Class java.Constructor java.reflect.

class Method { Method[] getDeclaredMethods().).. float..Few Important classes and Methods class Class { class Field { Constructor[] getConstructors(). } Field[] getDeclaredFields().. public boolean isPrimitive(). public boolean isInterface().. Field getDeclaredField(String name).. Class getReturnType(). } Note: You can pass int. Class getType().class. Constructor<T> getConstructor(Class….class etc to get Method.class. . void.. } . Constructor . Method getMethod(String name..) . Class …. Class[] getParameterTypes().

dirs system property) It is implemented by the sun. When the JVM is started. on demand.ext.misc. JRE does not need to know about files and file systems because of class loaders. .Launcher$AppClassLoader class. System class loader Loads classes found in $CLASSPATH. three class loaders are used: Bootstrap class loader Loads core Java Libraries located in $JAVE_HOME/lib directory Written in Native code Extensions class loader Loads the lib in extension directories $JAVA_HOME>/lib/ext or specified by the java. It is implemented by the sun.Class Loader – Brief Intro Java Classloader is a loads Java classes dynamically into the Java Virtual Machine.misc.

mysql.jdbc.Driver " class itself.Driver dynamically at runtime). Class.mysql.Driver") returns the Class object associated with the " com.jdbc.DriverManager.mysql.Driver") loads class com. The returned Class object is not an instance of the " com.jdbc.jdbc. } } *Problem with above approach . static{ try { java.mysql.Class.mysql.jdbc.jdbc.mysql.Driver") causes the class be initialized (JVM executes all its static block after class loading).forName("com.sql.forName("com.registerDriver(new Driver()).Driver " class. } catch (SQLException E) { throw new RuntimeException("Can't register driver!"). A call to forName(“com.forName ? Class.

Plugin File Name Why is it required to have plugin description file? What should we have in plugin description file pluginId=org.meru.MeruCab jarName=meruCab.0a .MeruCab pluginName=MeruCab className=com.bial.meru.cab.jar versionNumber=1.bial.cab.

How do I use this
class CabManager {

public static ICab load(String pluginFileName) throws
Exception {
Properties props = new Properties();
props.load(new FileInputStream(new File(pluginFileName));
String className = props.getProperty(“className”);
Class c = Class.forName(className);
return (ICar)c.newInstance();

}
}

Loading File from Jar
public static Class loadfromJar(String jarFilePath, String
Exception {

className) throws

Class clazz = null;
File file = new File(jarFilePath);
URL url = null;
String jarUrlString = "jar:" + file.toURI() + "!/";
url = new URL(jarUrlString);
URLClassLoader loader = new URLClassLoader(new URL[]
clazz = loader.loadClass(className);
return clazz;
}

{ url });

Mystery of Missing Default Constructor
Method to get specific constructor Class.getConstructor(Class[] parameterTypes);
Then call Constructor.newInstance(Object[] parameters);
Example:
public class MyClass{
public MyClass(String arg0, int arg1){
//Do something with args
}
}
Class c = Class.forName(“MyClass”);
Constructor<MyClass> myClassCons = c.getConstructor(String.class,
myClassCons.newInstance(“Test”, 5);

int.class);

invoke(obj.invoke(Object target. Class[] parameterTypes). Object[] parameters). method.getClass(). 2. new Class[]{String.class}).getMethod(“getLastName”. Method method = method. Method method = Class. Object result= method . Class[]parameterTypes). It is similar to Constructor 1. Class c = obj. public Method[] getDeclaredMethods(). new Object[]{“Allahbaksh”}).getMethod(String methodName. public Method getDeclaredMethod(String methodName. .Invoking Methods Not a rocket science.

it use to use reflection to get the method name which starts with test ◦ JUnit 4. JUnit ◦ Till JUnit 3. can take constructor arguments.Example of Reflections in real world Spring ◦ DI frame work ◦ Uses reflection to create objects.0 Uses annotation to decide the same Banking Software's ◦ Use reflection heavily .

Example from Wikipedia . Proxy objects are usually declared so that the client objects have no indication that they have a proxy object instance. Proxy pattern as you know is useful every where...Proxy Proxy is a pattern which has been there for long time. which acts as a surrogate or delegate for the underlying object being proxied. (Like we do it in class) Proxy act as an intermediary between a client object and a target object. A proxy forces object method calls to occur indirectly through the proxy object.

reflect.InvocationHandler.Dynamic Proxy It is useful to dynamically generate the bytecodes for the proxy class at runtime. Java provides reflection API to generate the Dynamic Proxy .reflect.newProxyInstance . This reduces amount of boiler plate code which we write.invoke ava.lang. This is used in many framework Two Major classes to create Dynamic Classes in Java java.lang.Proxy.

final.Proxy Proxy instance has an associated invocation handler object.3 supports the creation of dynamic proxy classes and instances.Proxy Some Details Java 1.lang. A dynamic proxy class is a class that implements a list of interfaces specified at runtime when the class is created The instanceof on proxy object gives proxy instance.reflect. Method invocation on a proxy object is passed through one of its proxy interfaces will be dispatched to the invoke() method of the instance's invocation handler . non-abstract subclasses of java. Proxy classes are public.

Some of the Usage Aspect Oriented Programming Security Dynamic Behavior Adding Logger RMI .

You can’t refactor your code easily .Don’t Use Reflection When you use reflection your IDE can’t see it.

Enterprise Integration Patterns Gregor Hohpe defined a visual pattern language describing message-based enterprise integration solutions Pattern language comprises 65 patterns in 6 categories Message Construction Endpoint Application A Messaging Endpoints Message Message Routing Channel Messaging Channels Message Transformation Router Translator Endpoint Application B Monitoring System Management 112 .

Pattern: Request-Response Service Consumer and Provider (similar to RPC) ◦ Channels are unidirectional Two asynchronous point-to-point channels Separate request and response messages Consumer Request Provider Request Channel Reply Channel Response 113 .

Multiple consumers Each consumer has its own reply queue But how does the provider send the response? ◦ Could send to all consumers (very inefficient) ◦ Hard code (violates principle of context-free service) Consumer 1 Requests Requests Provider Request Channel Reply Channel 1 ? Reply Channel 2 Responses Consumer 2 114 .

Pattern: Return Address Consumer specifies Return Address (the reply channel) in the request message Service provider sends response message to specified channel Consumer 1 Reply Channel 1 Reply Channel 2 Provider Request Channel Reply Channel 1 Reply Channel 2 Responses Consumer 2 115 .

Load-balanced service providers Request message can be handled by multiple providers Point-to-point channel supports competing services Only one service receives each request message But what if the response messages are out of order? Provider 1 Consumer Request Channel ss Provider 2 Reply Channel 116 .

Pattern: Correlation Identifier Consumer assigns a unique identifier to each message ◦ Identifier can be an arbitrary ID. a business key Provider copies the ID to the response message Consumer can match request and response Consumer 1 2 2 1 1 2 Message Identifier Request Channel Provider 1 1 2 Provider 2 2 1 Reply Channel 2 1 Correlation Identifier 117 . a GUID.

119 . But how? ◦ Do not want to burden sender with decisionss ◦ Letting providers "pick out" messages requires coordination Order Messages Order Entry Widget Inv. ? Gadget Inv.Multiple specialised providers Each provider can only handle a specific type of message Route the request to the "appropriate" provider.

Order Entry Content Based Router Gadget Inv. but can be stateful.Pattern: Content-Based Router Insert a content-based router Routers forward incoming messages to different channels Message content not changed Mostly stateless. 120 . e. de-duper Order Messages Widget Inv.g.

? Gadget Inv. 121 .Composite messages How can we process a message that contains multiple elements? Order Message Order Entry Widget Inv.

Order Entry Splitter Gadget Inv.Pattern: Splitter & Router Use a splitter to break out the composite message into a series of individual messages Then use a router to route the individual messages as before Note that two patterns are composed Order Message Order Item 1 Order Items Widget Inv. Router Order Item 2 122 .

Producing a single response How to combine the results of individual but related messages? ◦ Messages can be out-of-order. ? Billing Gadget Inv. delayed ◦ Multiple conversations can be intermixed Order Item 1 Response 1 Confirmed Order Widget Inv. Order Item 2 Response 2 123 .

Order Item 2 Aggregator Response 2 124 . an Aggregator Collects and stores messages until a complete set has been received (completeness condition) Publishes a single message created from the individual messages (aggregation algorithm) Order Item 1 Response 1 Confirmed Order Widget Inv.Pattern: Aggregator Use a stateful filter. Billing Gadget Inv.

Communicating with multiple parties How to send a message to a dynamic set of recipients? And return a single response message? Vendor A Quotes Vendor B Request For Quote Best Quote ? Vendor C Aggregator 125 .

only returns one quote Pub-Sub channel Vendor A Quotes Vendor B Request For Quote Best Quote Vendor C Aggregator 126 .Pattern: Scatter-Gather Send message to a pub-sub channel Interested recipients subscribe to a "topic" Aggregator collects individual response messages ◦ may not wait for all quotes.

Complex composition Receive an order message Use splitter to create one message per item Send to scatter/gather which returns "best quote" message Aggregate to create quoted order message Pub-Sub channel Vendor A Quotes Vendor B Splitter Aggregator Quote request for each item Best Quote for each item Vendor C Aggregator 127 .

Microservices .

automated deployment. . intelligence in the endpoints.Microservice Architecture Microservice Architecture describe a particular way of designing software applications as suites of independently deployable services. While there is no precise definition of this architectural style. there are certain common characteristics around organization around business capability. and decentralized control of languages and data.

Micro-service •Remotely accessible service (typically http) •Does “one thing” (and does it really well?) •Executes stand alone in a container •May depend on other services •Can be composed into a larger service •Small •Can be deployed independently •Loosely coupled •May be reusable may be not .

new framework.Why not Monolithic Apps grow (teams grow too!) Different modules change at different pace Different execution container needs different kind of resources (memory. CPU) Different modules are created by different teams? Teams are distributed across the globe Fear of deploying a change. . Risk of trying a new technique.

Smooth deployment Microservices need: Easy rollback No “over the wall” deployment Easy as-needed deployment Accessible deploy environment A PaaS can help (private or public) .

crisp conceptualization Services got very tiny (1000 line of code or so) Database segregated among services with or without sharing .Microservices Services are like Classes Small.

Summary of Microservices Very. very small Loosely coupled (including flow) Multiple versions acceptable (encouraged?) Self-execution monitoring of each service Publish interesting “stuff” (w/o requirement) “Application” seems to be poor conceptualization .