Sie sind auf Seite 1von 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

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,
interchangeable modules, such that each
contains everything necessary to execute only
one aspect of the desired functionality.

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 .Net world?


What are Layers?
Can modules exchange data?

List Down Advantages of Modular


Program?

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 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
attributevalue pairs. It is the primary data
format used for asynchronous browser/server
communication (AJAX), largely replacing XML.

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. By
doing so, these patterns increase flexibility in carrying out this communication.

Creational Patterns

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 comes with
a lot of implementation concerns.
Private constructor to restrict instantiation of the class from other classes.
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 comes with
a lot of implementation concerns.
Public static method that returns the object of the class, this is the global access point for outer
world to get the object of the singleton class.

Different approaches of Singleton pattern implementation and design concerns with the
implementation

Different Approach of Singleton


Eager initialization
Static block initialization
Lazy Initialization
Thread Safe Singleton
Using Reflection to destroy Singleton Pattern

Enum Singleton

Singleton Pattern Contd..


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.
Use only when Singleton class is not using a lot of resources.

It doesnt provide option for Exception handling.

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.
This makes it able to handle exception.

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

Factory Method
Encapsulate Object Creation. 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 - must instantiate classes but only knows about abstract
classes - which it cannot instantiate
Factory method encapsulates knowledge of which subclass to create - 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, MS Excel creates
spreadsheets

Abstract Factory
Provide an interface for creating objects without specifying their concrete classes
Example: Stacks, Queues, 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, e.g., Motif, PM
Abstract class for widget, supporting class for specific platform widget

package org.iiitj.abstractfactory;

package org.iiitj.abstractfactory;

public interface Button {


void paint();
}

public interface GUIFactory {


Button createButton();
Label createLabel();

package org.iiitj.abstractfactory;
public interface Label {
void paint();
}

package org.iiitj.abstractfactory;

package org.iiitj.abstractfactory;

public class Main {


public static void main(String[] args) {
new
Main().applicaiton(createOsSpecificFactory());
}
public static GUIFactory
createOsSpecificFactory() {
String osname =
System.getProperty("os.name").toLowerCase();
if(osname != null &&
osname.contains("windows"))
return new WinFactory();
else
return null;//new OSXFactory();
}

public class WinFactory implements GUIFactory {

public void applicaiton(GUIFactory factory){


Button button = factory.createButton();
}
}

@Override
public Button createButton() {
// TODO Auto-generated method stub
return null;
}
@Override
public Label createLabel() {
// TODO Auto-generated method stub
return null;
}
}

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, a set of Sets)
GUI layout (panels containing panels containing buttons, etc.)

42

Builder Pattern
The builder pattern is an object creation software design pattern.
The intention of the builder pattern is to find a solution to the telescoping constructor antipattern.
Instead of using numerous constructors, the builder pattern uses another object, a builder, that
receives each initialization parameter step by step and then returns the resulting constructed
object at once. It avoids telescoping of constructor.

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. In this pattern, your POJO has
numerous constructors each taking a different number of parameters that, if the class has been written
correctly, delegate to a default constructor.

Builder Pattern
1.

Create a Builder Class

2.

Each method in the Builder class will take and arguments or set of argument and return
object of the Builder class.

3.

After setting all the argument call the build method or create method.

4.

It returns Object of class for which Builder was created

Prototype
Specify the kinds of objects to create using a prototypical instance, 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 .clone(), which could be complicated sometimes in terms of shallow
copy and deep copy. Moreover, classes that have circular references to other classes cannot
really be cloned.

public class DVD implements Prototype{


private String name;
private float size;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public float getSize() {
return size;
}
public void setFloat(float inSize) {
size = inSize;
}
public Prototype clone() throws
CloneNotSupportedException {
return (DVD)super.clone();
}
}

public class CD implements Prototype {


private String name = null;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
@Override
public Prototype clone() throws
CloneNotSupportedException {
// TODO Auto-generated method stub
return (CD)super.clone();
}
}

Structural Patterns

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.

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

Lets see how do we do it


public interface Employee {
public void add(Employee employee);
public void remove(Employee employee);
public Employee getChild(int i);
public String getName();

public double getSalary();


public void print();
}

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

package org.iiitj.facade;

package org.iiitj.facade;

public class ComputerFacade {


private CPU processor;
private Memory ram;
private HardDrive hd;

public class CPU {


public void freeze(){

public ComputerFacade() {
processor = new CPU();
ram = new Memory();
hd = new HardDrive();
}
public void doSomeWork() {
processor.freeze();
processor.freeze();
ram.load(BOOT_ADDRESS, hd.read(BOOT_SECTOR,
SECTOR_SIZE));
processor.jump(BOOT_ADDRESS);
processor.execute();
}

public void jump(long memoryPosition){

}
public void execute(){
}

package org.iiitj.facade;
public
public
//TODO
object
return
}
}

class HardDrive {
byte[] read(long location, int size){
some implementation here and return
here
null;

package org.iiitj.facade;
public class Memory {
public void load(long position, byte[] data) {
}
}

Decorator Pattern (

objects that wrap around other objects to add useful features

53

Decorator Pattern
Decorator: an object that modifies behavior of, or adds features to, 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, scroll bars and borders to GUI controls

54

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.

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, and it is common practice to hold them in
external data structures and pass them to the flyweight objects temporarily when they are used.

package org.iiitj.flyweight;

package org.iiitj.flyweight;

public class CoffeeFlavour {


private final String name;
private float price;
public String getName() {
return name;
}
public float getPrice() {
return price;
}

import java.util.HashMap;
import java.util.Map;

public void setPrice(float inPrice){


price= inPrice;
}
public CoffeeFlavour(String name) {
super();
this.name = name;
}
}

public class Menu {


private Map<String, CoffeeFlavour> flavours = new
HashMap<String, CoffeeFlavour>();
CoffeeFlavour lookup(String flavorName, float price) {
if (!flavours.containsKey(flavorName))
flavours.put(flavorName, new
CoffeeFlavour(flavorName));
return flavours.get(flavorName);
}
int totalCoffeeFlavoursMade() {
return flavours.size();
}
}

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

External Iterator vs Internal Iterator


Clients that use an external iterator must advance the traversal and request the next element
explicitly from the iterator.

In contrast, the client hands an internal iterator an operation to perform, and the iterator
applies that operation to every element in the aggregate.
External iterators are more flexible than internal iterators.
It's easy to compare two collections for equality with an external iterator.

Iteration using internal iterators is often much easier to implement, because the iterator
implementation doesn't have to explicitly store and manage the state of the iteration.

package org.iiitj.iterators;
public class Employee {
}

public class EmployeeIterator implements


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

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, weather stats, and forcasts
measurementsChanged is called any time data changes, we dont 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

Loose Coupling
When two object are loosley coupled, 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

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

68

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, 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 example: Card player


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

70

// uses strategy

REST Web Services


ALLAHBAKSH ASADULLAH

Introduction to REST
Representational
Clients possess the information necessary to identify, modify, and/or delete a web resource.

State
All resource state information is stored on the client.

Transfer
Client state is passed from the client to the service through HTTP.

Introduction to REST
The six characteristics of REST:
1.

Uniform interface

2.

Decoupled client-server interaction

3.

Stateless

4.

Cacheable

5.

Layered

6.

Extensible through code on demand (optional)

* Services that do not conform to the above required constraints are not strictly RESTful web
services.

HTTP-REST Request Basics


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

HTTP-REST Request Basics


Sample Client Requests:
A typical client GET request:
GET /view?id=1 HTTP/1.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.1
User-Agent: IE
Request Headers
Content-Type: application/x-www-form-urlencoded
[CRLF]
name=x&id=2
Request Body (e.g. form parameters)

HTTP-REST Response Basics


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

HTTP-REST Response Basics


Sample Server Responses:
Response Status
HTTP/1.1 200 OK
Content-Type: text/html
Response Headers
Content-Length: 1337
[CRLF]
<html>
<!-- Some HTML Content. -->
Response Body (content)
</html>

HTTP/1.1 500 Internal Server Error


Response Status
HTTP/1.1 201 Created
Location: /view/7
Response Header
[CRLF]
Response Body
Some message goes here.

Response Status

HTTP-REST Vocabulary
HTTP Methods supported by REST:
GET Requests a resource at the request URL
Should not contain a request body, as it will be discarded.
May be cached locally or on the server.
May produce a resource, but should not modify on it.
POST Submits information to the service for processing
Should typically return the new or modified resource.
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

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.
The path and query string can be used to identify and customize the accessed resource.

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.g. GET, POST)


Supplied path information (e.g /service/listItems)
Query, form, and path parameters
Headers, cookies, etc.

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.
Requires a lot of boiler plate code for complex services.
Using a REST service framework.
Eliminates the need to write boilerplate code.
Typically integrates with other technologies, such as Spring.
Java provides the JAX-RS specification for use by providers of REST service frameworks.

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)

Designing services with a Uniform


Interface
/students
GET - list all students
POST - submit a new order

/students/{studentId}
GET - get an student representation
PUT - update an student info
DELETE delete a student info

/student/average-marks
GET - calculate average marks of students

/faculty
GET - list all faculty
POST - create a new faculty

/ faculty /{faculty-id}
GET - get a faculty details
DELETE- remove a faculty details

/ faculty /{facutly-id}/courses
GET - get the courses offered by a faculty

JAX-RS Annotations
@Path
Defines URI mappings and templates

@Produces, @Consumes
What MIME types does the resource produce and consume

@GET, @POST, @DELETE, @PUT, @HEADER


Identifies which HTTP method the Java method is interested in

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

Extensible Application Definition


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

What is an Extensible Application*


Just by adding the new JAR onto the application class path or into the
application specific extension directory, we can add new functionalities or APIs
to the application.
An application with extensible services will allow us, vendors, and perhaps even
customers to add service providers without modifying the original application.

*In our context

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, KM etc.
New Cab Provider register themselves with Airport

Airport Software need modification?

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

Some Config or Module Files


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

Driver to Drive the Cab


ServiceLoader<ICab>loader = ServiceLoader.load(ICab.class);
Iterator<ICab> cabIterator = loader.iterator();
while (cabIterator.hasNext()) {
ICab car = carIterator.next();

// Do something with Cab objects


}

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, or reflects, the classes, interfaces, and objects in
the current Java virtual machine.
It consists of metadata plus operations to manipulate the metadata.

Metadata a Bird Eye View


Metadata classes in Java
java.lang.Class
java.lang.reflect.Constructor
java.lang.reflect.Field
java.lang.reflect.Method

Few Important classes and Methods


class Class {

class Field {

Constructor[] getConstructors();

Class getType();

Constructor<T> getConstructor(Class..)

...

Field getDeclaredField(String name);

Field[] getDeclaredFields();

class Method {

Method[] getDeclaredMethods();

Class[] getParameterTypes();

Method getMethod(String name, Class .);

Class getReturnType();

public boolean isInterface();

...

public boolean isPrimitive();

...
}

Note: You can pass int.class, void.class, float.class etc to get


Method, Constructor

Class Loader Brief Intro


Java Classloader is a loads Java classes dynamically into the Java Virtual Machine, on demand. JRE does not
need to know about files and file systems because of class loaders.
When the JVM is started, 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.ext.dirs system property)

It is implemented by the sun.misc.


System class loader
Loads classes found in $CLASSPATH.
It is implemented by the sun.misc.Launcher$AppClassLoader

class.

Class.forName ?
Class.forName("com.mysql.jdbc.Driver") loads class com.mysql.jdbc.Driver dynamically at
runtime).
A call to forName(com.mysql.jdbc.Driver") causes the class be initialized (JVM executes all its static
block after class loading).
Class.forName("com.mysql.jdbc.Driver") returns the Class object associated with the "
com.mysql.jdbc.Driver " class. The returned Class object is not an instance of the "
com.mysql.jdbc.Driver " class itself.

static{
try {
java.sql.DriverManager.registerDriver(new Driver());
} catch (SQLException E) {
throw new RuntimeException("Can't register driver!");
}
}
*Problem with above approach

Plugin File Name


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

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);

Invoking Methods
Not a rocket science. It is similar to Constructor
1.

Method method = Class.getMethod(String methodName,


Class[]parameterTypes);

2.

method.invoke(Object target, Object[] parameters);

Class c = obj.getClass();
Method method = method.getMethod(getLastName,
new Class[]{String.class});

Object result= method .invoke(obj, new Object[]{Allahbaksh});

public Method getDeclaredMethod(String methodName,


Class[] parameterTypes);
public Method[] getDeclaredMethods();

Example of Reflections in real world


Spring
DI frame work
Uses reflection to create objects, can take constructor arguments,

JUnit
Till JUnit 3, it use to use reflection to get the method name which starts with test
JUnit 4.0 Uses annotation to decide the same

Banking Software's
Use reflection heavily

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

Dynamic Proxy
It is useful to dynamically generate the bytecodes for the proxy class at runtime.
This reduces amount of boiler plate code which we write.
Java provides reflection API to generate the Dynamic Proxy .
This is used in many framework

Two Major classes to create Dynamic Classes in Java


java.lang.reflect.InvocationHandler.invoke
ava.lang.reflect.Proxy.newProxyInstance

Proxy Some Details


Java 1.3 supports the creation of dynamic proxy classes and instances.
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.
Proxy classes are public, final, non-abstract subclasses of
java.lang.reflect.Proxy
Proxy instance has an associated invocation handler object.
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

Some of the Usage


Aspect Oriented Programming
Security
Dynamic Behavior Adding
Logger
RMI

Dont Use Reflection


When you use reflection your IDE cant see it. You cant refactor your code easily

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 GUID, a business key
Provider copies the ID to the response message
Consumer can match request and response
Consumer
1

Message
Identifier
Request Channel

Provider 1
1

Provider 2
2

1
Reply Channel

Correlation
Identifier

117

Multiple specialised providers


Each provider can only handle a specific type of message
Route the request to the "appropriate" provider. 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.

119

Pattern: Content-Based Router


Insert a content-based router
Routers forward incoming messages to different channels
Message content not changed
Mostly stateless, but can be stateful, e.g. de-duper
Order Messages

Widget Inv.

Order
Entry
Content
Based
Router

Gadget Inv.

120

Composite messages
How can we process a message that contains multiple elements?

Order
Message

Order
Entry

Widget Inv.

?
Gadget Inv.

121

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.

Order
Entry
Splitter

Gadget 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, delayed
Multiple conversations can be intermixed

Order
Item 1

Response 1

Confirmed
Order

Widget Inv.

Billing

Gadget Inv.
Order
Item 2

Response 2

123

Pattern: Aggregator
Use a stateful filter, 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.

Billing
Gadget Inv.
Order
Item 2

Aggregator
Response 2

124

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

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, only returns one quote
Pub-Sub
channel

Vendor A

Quotes

Vendor B
Request
For Quote

Best
Quote

Vendor C

Aggregator

126

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

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,
automated deployment, intelligence in the endpoints, 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

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, new framework.

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)

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

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

Das könnte Ihnen auch gefallen