Beruflich Dokumente
Kultur Dokumente
ALLAHBAKSH ASADULLAH
Agenda
1.
2.
3.
4.
5.
6.
Micro-service Architecture
7.
Rules of class
What is your
Observation
Book a Cab
Menu
OBSERVATIONS
Menu should be pluggable
Focus Essential
It should extensible (add new menu)
Ease of use
Feedback
OBSERVATIONS
Fares
OBSERVATIONS
Profile
OBSERVATIONS
Load
Balan
cer
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.
Is Jar a module?
JSON
OO Design Pattern
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
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
Enum Singleton
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;
package org.iiitj.abstractfactory;
public interface Label {
void paint();
}
package org.iiitj.abstractfactory;
package org.iiitj.abstractfactory;
@Override
public Button createButton() {
// TODO Auto-generated method stub
return null;
}
@Override
public Label createLabel() {
// TODO Auto-generated method stub
return null;
}
}
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.
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.
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.
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
Manager
Developer
Developer
Developer
48
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 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 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 (
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
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;
import java.util.HashMap;
import java.util.Map;
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, 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 {
}
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
c.
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 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?
69
70
// uses strategy
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.
3.
Stateless
4.
Cacheable
5.
Layered
6.
* Services that do not conform to the above required constraints are not strictly RESTful web
services.
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.
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)
/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
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
Hbase
Zoo Keeper
Ambari
Pig
Hive
Mahout
Pig
Hive
Tez
Mahout
Shark
Impala
YARN
HDFS 2
Giraph
GraphX
Spark
MLib
Open
MPI
Sazma
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.
class Field {
Constructor[] getConstructors();
Class getType();
Constructor<T> getConstructor(Class..)
...
Field[] getDeclaredFields();
class Method {
Method[] getDeclaredMethods();
Class[] getParameterTypes();
Class getReturnType();
...
...
}
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
}
}
className) throws
{ url });
int.class);
Invoking Methods
Not a rocket science. It is similar to Constructor
1.
2.
Class c = obj.getClass();
Method method = method.getMethod(getLastName,
new Class[]{String.class});
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
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
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
Consumer 1
Reply
Channel 1
Reply
Channel 2
Provider
Request Channel
Reply Channel 1
Reply Channel 2
Responses
Consumer 2
115
Consumer
Request Channel
ss
Provider 2
Reply Channel
116
Message
Identifier
Request Channel
Provider 1
1
Provider 2
2
1
Reply Channel
Correlation
Identifier
117
Order Messages
Order
Entry
Widget Inv.
?
Gadget Inv.
119
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
Order
Message
Order
Item 1
Order
Items
Widget Inv.
Order
Entry
Splitter
Gadget Inv.
Router
Order
Item 2
122
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
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
Smooth deployment
Microservices need:
Easy rollback
No over the wall deployment
Easy as-needed deployment
Accessible deploy environment
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)