Upload
ashish-meena
View
19
Download
0
Tags:
Embed Size (px)
DESCRIPTION
dgdhgdnknddfnvgdkbgdn
Citation preview
Modular Software DesignALLAHBAKSH ASADULLAH
Agenda1. 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 LoginOBSERVATIONS
Book a Cab
Menu OBSERVATIONS
Menu should be pluggable
Focus Essential
It should extensible (add new menu)
Ease of use
Check your BookingOBSERVATIONS
FeedbackOBSERVATIONS
FaresOBSERVATIONS
ProfileOBSERVATIONS
Some more things to Observe
Some more things…
Lets see a broader Picture
Now we have to see how
A view of the ArchitectureREST based
Web Service
Data
base
HIG
H L
EV
EL
AP
I
C
a
c
h
e
REST based
Web Service
REST based
Web Service
REST based
Web Service
Load
Balan
cer
Payment
Gateways
Module?Module is a set of standardized parts orindependent units that can be used toconstruct a more complex structure, such asan item of furniture or a building.
Modular programming is a software designtechnique that emphasizes separating thefunctionality of a program into independent,interchangeable modules, such that eachcontains everything necessary to execute onlyone aspect of the desired functionality.
Can we define good programWhat should be idle size of a class?
How many methods a class should have ideally?
◦ 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?
Whether Java has module system?
Is Jar a module?
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
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
JSON
JavaScript Object Notation, is an open standard format that uses human-readable text to transmit data objects consisting of attribute–value pairs. It is the primary data format used for asynchronous browser/server communication (AJAX), largely replacing XML.
OO Design Pattern
Object Oriented (OO) BasicsAbstraction
Encapsulation
Inheritance
Polymorphism
OO PrinciplesEncapsulate 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
SingletonSingleton 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.
SingletonSingleton 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 SingletonEager 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 doesn’t provide option for Exception handling.
Singleton with Static InitStatic 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 SingletonThis 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 FactoryProvide 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;
public interface Button {void paint();}
package org.iiitj.abstractfactory;
public interface GUIFactory {Button createButton();Label createLabel();
}
package org.iiitj.abstractfactory;
public interface Label {void paint();}
package org.iiitj.abstractfactory;
public class Main {public static void main(String[] args) {newMain().applicaiton(createOsSpecificFactory());}public static GUIFactorycreateOsSpecificFactory() {String osname = System.getProperty("os.name").toLowerCase();if(osname != null && osname.contains("windows"))return new WinFactory();elsereturn null;//new OSXFactory();}
public void applicaiton(GUIFactory factory){Button button = factory.createButton();
}}
package org.iiitj.abstractfactory;
public class WinFactory implements GUIFactory {
@Overridepublic Button createButton() {// TODO Auto-generated method stubreturn null;}
@Overridepublic Label createLabel() {// TODO Auto-generated method stubreturn 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 PatternThe builder pattern is an object creation software design pattern.
The intention of the builder pattern is to find a solution to the telescoping constructor anti-pattern.
Instead of using numerous constructors, the builder pattern uses another object, a builder, thatreceives each initialization parameter step by step and then returns the resulting constructedobject 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 toooften used in projects even though there are better alternatives availble. In this pattern, your POJO hasnumerous constructors each taking a different number of parameters that, if the class has been writtencorrectly, delegate to a default constructor.
Builder Pattern1. 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
PrototypeSpecify 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() throwsCloneNotSupportedException {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;}
@Overridepublic Prototype clone() throwsCloneNotSupportedException {// TODO Auto-generated method stubreturn (CD)super.clone();}
}
Structural Patterns
Composite patternThe composite pattern describes that a groupof objects is to be treated in the same way as asingle instance of an object.
The intent of a composite is to "compose"objects into tree structures to represent part-whole hierarchies.
Implementing the composite pattern letsclients treat individual objects andcompositions uniformly.
48
General Manager
Manager
Developer Developer
Developer
Lets see how do we do itpublic 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();
}
FacadeA 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;
public class ComputerFacade {private CPU processor;private Memory ram;private HardDrive hd;
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();}
}
package org.iiitj.facade;
public class CPU {public void freeze(){
}
public void jump(long memoryPosition){
}
public void execute(){
}
}
package org.iiitj.facade;
public class HardDrive {public byte[] read(long location, int size){//TODO some implementation here and return object herereturn 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
54
Decorator PatternDecorator: 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 theinterface 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
55
Decorator example: I/ONormal 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
Flyweight PatternA 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;
public class CoffeeFlavour {private final String name;private float price;public String getName() {return name;}public float getPrice() {return price;}
public void setPrice(float inPrice){price= inPrice;}public CoffeeFlavour(String name) {super();this.name = name;
}
}
package org.iiitj.flyweight;
import java.util.HashMap;import java.util.Map;
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
59
Iterator patternIterator an object that provides a standard way to examine all elements of any collection
Uniform interface for traversing many different data structures without exposing theirimplementations (java.util.Iterator<E>)
Supports concurrent iteration and element removal
Removes need to know about internal structure of collection or different methods to accessdata from different collections
External Iterator vs Internal IteratorClients 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 iteratorapplies 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 iteratorimplementation doesn't have to explicitly store and manage the state of the iteration.
package org.iiitj.iterators;
public class Employee {
}
public class EmployeeIterator implementsIterator<Employee> {private List<Employee> list;private int elementIndex;public EmployeeIterator(List<Employee> inList) {list = inList;}@Overridepublic boolean hasNext() {try{Employee employee = list.get(elementIndex);}catch(Exception e){return false;}return true;}@Overridepublic Employee next() {Employee employee = list.get(elementIndex);elementIndex++;return employee;}
Template Pattern•Defines a program skeleton of an algorithm ina method, called template method, whichdefers some steps to subclasses.
•Redefine certain steps of an algorithm without changing the algorithm's structure
a. Define an abstract class with steps of eachalgorithm as method
b. The order in which each step has to beexecuted is put in the final method ofabstract class.
c. You can not change the order of theimplementation is called
The Observer Pattern
The Weather Monitoring ExampleThe Weather Monitoring application
The Weather Monitoring ExampleTask◦ 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 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
ObserverSometimes 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 CouplingWhen 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: Strategyobjects that hold alternate algorithms to solve a problem
68
69
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
Strategy pattern
70
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(); // uses strategy
REST Web ServicesALLAHBAKSH ASADULLAH
Introduction to RESTRepresentational◦ 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 RESTThe 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 BasicsThe 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 BasicsSample Client Requests:
A typical client GET request:
A typical client POST request:
GET /view?id=1 HTTP/1.1
User-Agent: Chrome
Accept: application/json
[CRLF]
POST /save HTTP/1.1
User-Agent: IE
Content-Type: application/x-www-form-urlencoded
[CRLF]
name=x&id=2
Requested Resource (path and query string)
Request Headers
Request Body (e.g. form parameters)
Requested Resource (typically no query string)
Request Headers
(no request body)
HTTP-REST Response BasicsThe 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 BasicsSample Server Responses:
HTTP/1.1 200 OK
Content-Type: text/html
Content-Length: 1337
[CRLF]
<html>
<!-- Some HTML Content. -->
</html>
HTTP/1.1 500 Internal Server Error
HTTP/1.1 201 Created
Location: /view/7
[CRLF]
Some message goes here.
Response Status
Response Headers
Response Body (content)
Response Status
Response Header
Response Body
Response Status
HTTP-REST VocabularyHTTP 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 VocabularyA typical HTTP REST URL
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://<WebSiteName>/location/list?category=prof&limit=20
protocol host name path to a resource query string
HTTP and RESTA 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 ServicesREST 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 StackAlthough 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
85
Request
(XML doc)
Response
(XML doc)
Web
/Pro
xy S
erver
HTTP GETURL 1
HTTP Response
doGet()
Request
(XML doc)
Response
(JSON doc)
HTTP POSTURL 1
HTTP Response
doPost(id)
REST Engine
(locate resource
and generate
response)
PO
(XML doc)
HTTP DELETEURL 1
doDelete()
Response
(TEXT doc)HTTP Response
Architecture Style
A Layered Diagram of Big Data Platform(Exampleof Layers)
HDFS 2
Hb
ase
Hyp
erta
ble
YARN
Hadoop Map Reduce
Pig Hive Mahout
Tez
Pig Hive Mahout
Impala Giraph Spark
Shark GraphX MLib
Open MPI
Sazma
Zoo
Kee
per
Am
bar
i
Building Extensible Applications
Extensible Application Definition
Without modifying the core application, extending the application is know as extensibleapplication.
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 theapplication specific extension directory, we can add new functionalities or APIsto the application.
An application with extensible services will allow us, vendors, and perhaps evencustomers 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 ServiceAirport 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 FilesCreate 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 classnameon 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 observeand/or manipulate the inner workings of the environment programmatically.”
“The reflection API represents, or reflects, the classes, interfaces, and objects inthe 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 Methodsclass Class {
Constructor[] getConstructors();
Constructor<T> getConstructor(Class…..)
Field getDeclaredField(String name);
Field[] getDeclaredFields();
Method[] getDeclaredMethods();
Method getMethod(String name, Class ….);
public boolean isInterface();
public boolean isPrimitive();
...
}
class Field {
Class getType();
...
}
class Method {
Class[] getParameterTypes();
Class getReturnType();
...
}
Note: You can pass int.class, void.class, float.class etc to get Method, Constructor
Class Loader – Brief IntroJava Classloader is a loads Java classes dynamically into the Java Virtual Machine, on demand. JRE does notneed 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 NameWhy 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 thisclass 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 Jarpublic static Class loadfromJar(String jarFilePath, String className) throws Exception {
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[] { url });
clazz = loader.loadClass(className);
return clazz;
}
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, int.class);
myClassCons.newInstance(“Test”, 5);
Invoking MethodsNot 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
ProxyProxy 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 asurrogate or delegate for the underlying object being proxied. Proxy objects are usually declaredso that the client objects have no indication that they have a proxy object instance. (Like we doit in class)
Proxy act as an intermediary between a client object and a target object.
Example from Wikipedia
Dynamic ProxyIt 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 DetailsJava 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 whenthe 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 UsageAspect Oriented Programming
Security
Dynamic Behavior Adding
Logger
RMI
Don’t Use ReflectionWhen you use reflection your IDE can’t see it. You can’t refactor your code easily
Enterprise Integration PatternsGregor Hohpe defined a visual pattern language describing message-based enterprise
integration solutions
Pattern language comprises 65 patterns in 6 categories
112
Application
A
Application
B
MessageChannel
Router TranslatorEndpoint Endpoint
MonitoringMessagingEndpoints
MessagingChannels
MessageConstruction
MessageRouting
MessageTransformation
SystemManagement
Pattern: Request-ResponseService Consumer and Provider (similar to RPC)
◦ Channels are unidirectional
Two asynchronous point-to-point channels
Separate request and response messages
113
Request Channel
Response
Request
Reply Channel
ProviderConsumer
Multiple consumersEach 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)
114
Responses
Requests
?
Requests
Request Channel
Reply Channel 1
Reply Channel 2
ProviderConsumer 1
Consumer 2
Pattern: Return AddressConsumer specifies Return Address (the reply channel) in the request message
Service provider sends response message to specified channel
115
Responses
Reply
Channel 1Reply
Channel 2
Request Channel
Reply Channel 1
Reply Channel 2
ProviderConsumer 1
Consumer 2
Load-balanced service providersRequest 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?
116
ssRequest Channel
Reply Channel
Provider 1
Provider 2
Consumer
Pattern: Correlation IdentifierConsumer 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
117
Message
Identifier 1
2
1 2
12 12
1 2
12
Correlation
Identifier
Request Channel
Reply Channel
Provider 1
Provider 2
Consumer
Multiple specialised providersEach 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
119
Order
Entry
Widget Inv.
?
Order Messages
Gadget Inv.
Pattern: Content-Based RouterInsert 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
120
Order
Entry
Widget Inv.Order Messages
Gadget Inv.Content
Based
Router
Composite messagesHow can we process a message that contains multiple elements?
121
Order
Entry?
Order
MessageWidget Inv.
Gadget Inv.
Pattern: Splitter & RouterUse 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
122
Widget Inv.
Gadget Inv.
Order
Entry
RouterSplitter
Order
MessageOrder
Items
Order
Item 1
Order
Item 2
Producing a single responseHow to combine the results of individual but related messages?
◦ Messages can be out-of-order, delayed
◦ Multiple conversations can be intermixed
123
Widget Inv.
Gadget Inv.
Billing
Order
Item 1 Response 1
Order
Item 2Response 2
Confirmed
Order
?
Pattern: AggregatorUse 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)
124
Widget Inv.
Gadget Inv.
Billing
Aggregator
Order
Item 1 Response 1
Order
Item 2Response 2
Confirmed
Order
Communicating with multiple partiesHow to send a message to a dynamic set of recipients?
And return a single response message?
125
Request
For Quote
Vendor A
Vendor B
Quotes
AggregatorBest
Quote
Vendor C?
Pattern: Scatter-GatherSend 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
126
Request
For Quote
Vendor A
Vendor B
Quotes
AggregatorBest
Quote
Vendor C
Pub-Sub
channel
Complex compositionReceive 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
127
Quote request
for each item
Vendor A
Vendor B
Quotes
AggregatorBest Quote
for each item
Vendor C
Aggregator
Splitter
Pub-Sub
channel
Microservices
Microservice ArchitectureMicroservice 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 MonolithicApps 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 deploymentMicroservices need:
Easy rollback
No “over the wall” deployment
Easy as-needed deployment
Accessible deploy environment
A PaaS can help (private or public)
MicroservicesServices 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 MicroservicesVery, 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