SlideShare a Scribd company logo
Design Patterns
Vivek Gohil
SOLID Principles
• Single Responsibility Principle
• Open Closed Principle
• Liskov Substitution Principle
• Interface Segregation Principle
• Dependency Inversion Principle
Single Responsibility Principle
• There should never be more than one reason for a class to change
• The class provides a very focused functionality.
• It addresses a specific concern of our desired functionality.
Open Closed Principle
• Software entities(Class , Modules, Methods) should be open for
extension but closed for modification.
• Open for extension : Extend existing behaviour(Create new class which
derived from base and override methods).
• Closed for modification : Existing code remains unchanged(Avoid modification
in base classes).
Liskov Substitution Principle
• Object of a superclass shall be replaceable with objects of its
subclasses without breaking the application.
Interface Segregation Principle
• Clients should not be forced to depend upon interfaces that they do
not use.
• This is also known as interface pollutions(Large and unrelated methods)
• Classes have empty method implementations
• Method implementations return null or default/dummy values.
• Write Highly Cohesive Interfaces.
Dependency Inversion Principle
• Part 1 : High level modules should not depend upon low level
modules. Both should depend upon abstractions.
• Part 2 : Abstractions should not depend upon details. Details should
depend upon abstractions.
Design Pattern
• Creational Design Pattern
• Creational patterns deal with the process of creation of objects of classes.
• Structural Design Pattern
• Structural patterns deal with how classes and objects are arranged or
composed.
• Behavioural Design Pattern
• Behavioural Design Patterns describe how classes and objects interact and
communicate with each other.
Creational Design Pattern
• Builder
• Simple Factory
• Factory Method
• Prototype
• Singleton
• Abstract Factory
• Object Pool
Builder Pattern
• What problem builder design pattern solves?
• Class constructor requires a lots of information
• Having a lots of arguments in constructor parameter is not a good practice.
• It also creates the confusion if the constructor parameter has same datatypes.
• Sometimes constructor also require some other class object as parameter.
//Product instances are immutable
class Product {
public Proudct(int weight, double price, int shipVolume, int
shipCode) {
// variable initialization
}
// other code
}
Builder Pattern
• Builder pattern make it easy to use such constructors so that we can
create objects of this class.
• It also help us avoid writing such constructors in first place and still
have our objects immutable.
Builder Pattern
• What is a Builder?
• We have a complex process to construct an object involving multiple steps,
then builder design pattern can help us.
• In builder we remove the logic related to object construction from “Client”
code and abstract it in separate classes
UML
UML
UML
UML
UML
Implement a Builder
• We start by creating a builder
• Identify the parts of the product and provide methods to create those parts
• It should provide a method to assemble or build the product/object
• It must provide a way/method to get fully built object out. Optionally builder
can keep reference to an product it has built the same can be returned again
in future.
• A director can be a separate class or client can play the role of
director.
Example UML
Simple Factory
• What problem simply factory solves?
• Multiple types can be instantiated, and the choice is based on simple criteria
if(key.equalsIgnoreCase("pudding")) {
// create pudding object
}
else if (key.equalsIgnoreCase("cake")) {
// create cake object
}
Simple Factory
• What is a Simple Factory?
• Here we simply move the instantiation logic to a separate class and most
commonly to a static method of this class.
• Some do not consider simple factory to be a “design pattern” as its simply a
method that encapsulates the object instantiation.
• Nothing complex goes on in that method.
• We are studying simple factory as it is often confused with “factory method” pattern
• Typically, we want to do this if we have more than one option when
instantiating object and a simple logic is used to choose correct class.
Simple Factory
Simple Factory
• Implement a Simple Factory
• We start by creating a separate class for our simple factory
• Add method with returns desired object instance.
• This method is typically static and will accept some argument to decide which class to
instantiate.
• You can also provide additional arguments which will be used to instantiate objects.
Simple Factory
• Implementation Considerations
• Simple factory can be just a method in existing class. Adding a separate class
however allows other parts of your code to use simple factory more easily.
• Simple factory itself doesn’t need any state tracking so its best to keep this as
a static method.
• Simple factory will in turn may use other design pattern like builder to
construct objects.
• In case you want o specialized your simple factory in sub classes , you need
factory method design pattern instead.
Simple Factory
• The java.text.NumberFormat class has getInstance method, which is
an example of simple factory.
Simple Factory
Simple Factory
• We simply move our
instantiation logic away from
client code. Typically, in a static
method.
• Simple factory knows about all
classes whose object it can
create.
Factory Method
• Factory method is more useful
when you want to delegate
object creation to subclasses.
• In Factory method we don’t
know in advance about all
products subclasses.
Simple Factory
• Pitfalls
• The criteria used by simple factory to decide which object to instantiate can
get more convoluted/complex over time.
• If you find yourself in such situation then use factory method design pattern.
Simple Factory
• Quiz
• Select correct/true statements regarding the simple factory pattern from
following statements.
• A simple factory assembles objects one part at a time.
• A simple factory allows to maintain single instance of a class in entire application.
• A simple factory can instantiate an object based on simple criteria.
• A simple factory saves JVM memory by pooling the objects.
• Select the benefits of implementing simple factory in a separate class.
• It allows simple factory to use inheritance and specialized object creation.
• It allows to reuses the simple factory by other classes without importing unrelated
classes.
Factory Method
• What is a factory method?
• We want to move the object creation logic from our code to separate class.
• We use this pattern when we do not know in advance which class we may
need to instantiate beforehand.
• Also to allow new classes to be added to system and handle their creation
without affecting client code.
• We let subclasses decide which object to instantiate by overriding the factory
method.
UML
UML
Factory Method
• Implement a Factory Method
• We start by creating a class for our creator
• Creator itself can be concreate if it can provide a default object or it can be abstract.
• Implementations will override the method and return object.
UML
Factory Method
• Implementation Considerations
• The creator can be a concrete class and provide a default implementation for
the factory method. In such cases you will create some default object in base
creator.
• You can use the simple factory way of accepting additional arguments to
choose between different object types. Subclasses the override factory
method to selectively create different object for some criteria.
Factory Method
• Design Considerations
• Creator hierarchy in factory method pattern reflets the product hierarchy.
• We typically end up with a concrete creator per object type.
• Template method design pattern often makes use of factory method.
• Another creational design pattern called ”abstract factory” makes use of
factory method pattern.
Factory Method
• Examples of a Factory Method
• The java.util.Collection(or java.util.AbstractCollection) has an abstract method
called iterator(). This method is an example of factory method.
Factory Method
• Pitfalls
• More complex to implement. More classes are involved and need unit testing.
• You have to start with Factory method design pattern from the beginning. It is
not easy to refactor existing code into factory method pattern.
• Sometimes this pattern forces you to subclass just to create appropriate
instance.
Factory Method
• Quiz
• Which statement describles the difference between “Factory Method” and
“Simple Factory” patterns?
• Factory method uses inheritance to specialize object creation and simple factory don’t
use inheritance.
• Factory method is always static method in a final class while simple factory always uses
non-static method.
• To support creation of a new type of object we need to modify existing factory method
pattern implementation while in simple factory pattern we add a new child class which
creates the new object.
• Factory Method pattern needs less number of classes to implement the Simple Factory
method pattern when working with same product hierarchy.
Factory Method
• Quiz
• What is a drawback of factory method pattern?
• We need to modify existing code of factory method pattern whenever a new product
class is added to system
• We often end up creating child classes just to instantiate a new object resulting in large
number of classes which need unit testing.
Prototype
• What is a Prototype?
• We have a complex object that is costly to create. To create more instances of
such class, We use and existing instance as our prototype.
• Prototype will allow us to make copies of existing objects and save us from
having to recreate objects from scratch.
UML
UML
Prototype
• Implement a Prototype
• We start by creating a class which will be a prototype
• The class must implement cloneable interface
• Class should override clone method and return copy of itself.
• The method should declare CloneNotSupportedException in thows clause to give
subclasses chance to decide on whether to support cloning.
• Clone method implementation should consider the deep and shallow copy
and choose whichever is applicable.
Prototype
• Implementation Considerations
• Pay attention to the deep copy and shallow copy of references.
• Immutable fields on clones save the trouble of deep copy.
• Make sure to reset the mutable state of objects before returning the
prototype. It’s a good idea to implement this in method to allow subclasses to
initialize themselves.
• Clone() method is protected in Object class and must be overridden to public
to be callable from outside the class.
• Cloneable is a marker interface
Prototype
• Design Considerations
• Prototypes are useful when you have large objects where majority of state is
unchanged between instances and you can easily identify that state.
• Prototypes are useful when working with Composits and Decorator Patterns
Prototype
• Actually the Object.clone() method is an example of a prototype!
Prototype
Prototype
• We return a copy of an instance,
meaning we get a new instance
• Some or even all of the state of
instances created with
prototypes can be different
Singleton
• We return same instance every
time.
• Since it’s the same object that is
returned state is always the
same.
Prototype
• Pitfalls
• Usability depends upon the number of properties in state that are immutable
or can be shallow copied.
• An object where state is comprised of large number of mutable objects is
complicated to clone.
• In java the default clone operation will only perform the shallow copy so if
you need a deep copy you must implement it.
• Subclasses may not be able to support clone and so the code becomes
complicated as you have to code for situations where an implementations my
not support clone.
Prototype
• Quiz
• Which of the following statement is true with regards to Prototype design
pattern?
• Prototype allows only one instance of the class to be created in entire application.
• An object created with prototype pattern can never be garbage collected.
• Prototype class must be declared as final to prevent inheritance.
• Prototype pattern copies an existing object to create separate new object
• Select the true statement from the following statements.
• The clone() method provided in the Object class performs deep copy of the object.
• The clone() method from Object needs to be overridden to make it public.
• The clone() method is declared in Cloneable interface.
• We can clone objects of any class in java.
Prototype
• Quiz
• Why we have to implement Cloneable interface in Prototype design pattern
• It is not mandatory and just good practice to implement cloneable!
• This interface adds the clone() method which is used to clone the object.
• If cloneable interface is not implemented then clone method throws exception.
• Cloneable needs to be implemented otherwise code dose not compile.
Singleton
• What is a Singleton?
• A singleton class has only one instance, accessible globally through a single
point.
• Main problem this pattern solves is to ensure that only a single instance of
this class exists.
• Any state you add in your singleton becomes apart of “global state” of your
application.
Singleton
• Implement a Singleton
• Controlling instance creation
• Class constructor(s) must be not be accessible globally
• Subclassing /inheritance must not be allowed
• Keeping track of instance
• Class itself is a good place to track the instance
• Giving access to the singleton instance
• A public static method is good choice
• Can expose instance as final public static fields but it wont work for all singleton
implementations.
Singleton
• Two options for implementing a singleton
• Early initialization – Eager Singleton
• Create singleton as soon as class is loaded
• Lazy initialization – Lazy Singleton
• Singleton is created when it is first required
Singleton
• Implementation Considerations
• Early/Eager initialization is the simplest and preferred way.
• The classic singleton pattern implementation uses double check locking and
volatile field.
• The lazy initialization holder idiom provides best of both worlds, you don’t
deal with synchronization issues directly and is easy to implement.
Singleton
• Design Considerations
• Singleton creation does not need any parameters. If you find yourself in need
of support for constructor arguments, you need a simple factory or factory
method pattern instead.
Singleton
• Example of a Singleton Pattern
• Java.lang.Runtime class in standard Java API is a singleton.
Singleton
• Singleton pattern can deceive you about true dependencies! Since
you are globally accessible its easy to miss dependencies.
• They are hard to unit test. You cannot easily mock the instance that is
returned.
• Most common way to implement singletons in Java is through static
variables and they are held per class loader and not per JVM. So they
may not be truly singleton.
Singleton
• Quiz
• What is Eager singleton?
• In eager singleton implementation the singleton instance is created as soon the singleton
class is referenced.
• In eager singleton implementation the singleton instance is created when some code
calls getInstance() method.
• In eager singleton implementation the singleton instance is created as soon as JVM
process starts.
• In eager singleton implementation the singleton instance is created when an instance
method is called on singleton reference.
Singleton
• Quiz
• What is double check locking that is used by lazy singleton implementation?
• Double check locking means we use two synchronization blocks, one inside another. We
also use volatile keyword to declare reference.
• We check twice for the singleton reference to be null, once before synchronization block
and then inside the synchronization block and we have to make sure the reference is
volatile.
• Two separate locks are declared in the singleton class and we have to ensure both locks
are locked to create singleton instance.
• We call getInstacen() method twice and check the return value.
Structural Design Pattern
• Adapter
• Bridge
• Decorator
• Composite
• Façade
• Flyweight
• Proxy
Adapter(aka Wrapper)
• What is Adapter?
• We have an existing object which provides the functionality that client needs.
But client cant use this object because it expects and object with different
interface.
• Using adapter design pattern we make this existing object work with client by
adapting the object to client’s expected interface.
• This pattern is also called as wrapper as its ”wraps” existing object.
UML – Class Adapter
UML – Class Adapter
UML – Object Adapter
UML – Object Adapter
Adapter
• Implement an Adapter
• We start by creating a class for Adapter
• Adapter must implement the interface expected by client.
• First we are going to try out a class adapter by also extending from our existing class.
• In the class adapter implementation we are simply going to forward the method to
another method inherited from adaptee.
• Next for object adapter , we are only going to implement target interface and accept
adaptee as constructor argument in adapter i.e. make use of composition.
• An object adapter should take adaptee as an argument in constructor or as
less preferred solution, you can instantiate it in the constructor thus tightly
coupling with a specific adaptee
Example UML – Class Adapter
Example : UML (Object Adapter)
Adapter
• Implementation Considerations
• How much work the adapter does depends upon the differences between
target interface and object being adapted.
• If method arguments are same or similar adapter has very less work to do.
Adapter
• In java a “class adapter” may not be possible if both target and
adaptee are concrete classes. In such cases the object adapter is the
only solution. Also since there is not private inheritance in java its
better to stick with object adapter.
• A class adapter is also called as a two way adapter, since it can stand
in for both the target interface and for the adaptee. That is we can
use object of adapter where either target interface is expected as well
as and adaptee object is expected.
Adapter
• Examples of an Adapter
• The java.io.InputStreamReader and OutputStreamWriter classes
Adapter
• Pitfalls
• Using target interface and adaptee class to extend our adapter we can create
a class adapter in java.
• However it create an object which exposes unrelated methods in parts of
your code, polluting it.
• Avoid class adapters.
Adapter
• Quiz
• Which one of the following scenarios is most suitable for using Adapter
design pattern?
• We want to add new functionality to a class without modifying original code.
• We have existing object the provide needed functionality but client code needs expects
different interface.
• We want to hide our real object for client.
• When we want to intercept method calls for logging and authantication.
Adapter
• Quiz
• Which one of the following is not NOT a type of adapter in Adapter Design
Pattern?
• Class Adapter
• Java Adapter
• Object Adapter
Decorator
• What is Decorator?
• When we want to enhance behaviour of our existing object dynamically as
and when required then we can use decorator design pattern.
• Decorator wraps an object within itself and provides same interface as the
wrapped object. So the client of original object doesn’t need to change.
• A decorator provides alternative to subclassing for extending functionality of
existing classes.
Decorator
Decorator
• Implement a Decorator
• We start with our component
• Component defines interface needed or already used by client.
• Concrete component implements the component.
• We define our decorator. Decorator implements components and also needs reference
to concrete component.
• In decorator methods we provide additional behaviour on top the provided by concrete
component instance.
• Decorator can be abstract as well & depend on subclasses to provide functionality.
Decorator
Decorator
• Implementation Considerations
• Since we have decorators and concrete class extending from common
component , avoid large state in this base class as decorators may not need all
that state.
• Pay attention to equals and hashCode methods of decorator. When using
decorators, you have to decide if decorated object is equal to same instance
without decorator.
• Decorator supports recursive composition and so this pattern lends itself to
creation of lots of small objects that add “just a little bit” functionality. Code
using these objects becomes difficult to debug.
Decorator
• Design Considerations
• Decorators are more flexible and powerful than inheritance.
• Inheritance is static by definition but decorators allow you to dynamically
compose behaviour using objects at runtime.
• Decorators should act like additional skin over your object. They should add
helpful small behaviours to objects original behaviour. Do not change the
meaning of operations.
Decorator
• Example of Decorator
• Classes in java I.O packages are great examples of decorator pattern.
• For example java.io.BufferedOutputStream class decorates any
java.io.OutputStream object and adds buffering to file writing operations.
Decorator
• Pitfalls
• Often result in large number of classes being added to system, Where each
class adds small amount of functionality.
• Sometimes new comers will start using it as a replacement of inheritance in
every scenario. Think of decorators as a thin skin existing objects.
Decorator
• Quiz
• What is the fundamental purpose behind using Decorator design pattern?
• It allows us to adapt existing object to a new interface expected by the client code.
• Add new functionality on top of what is provided by existing object.
• To completely change the functionality of existing object.
• Provide decorative formatting to objects textual representation.
• Decorators allows recursive composition. What exactly dose “Recursive composition”
means in this context?
• It means , a decorator can be composed with/wrap another decorator written for same object
which in turn can also wrap another decorator and so on.
• All decorator methods can be called recursively.
• The decorators call recursive methods on the original object.
• Its simply a single decorator containing the original object via composition. We cant compose a
decorator with another decorator.
Decorator
• Quiz
• Select the true/correct statements from below.
• A decorator changes the interface of the object which it decorates.
• A single decorator instead can be decorate multiple objects at the same time.
• A decorator cannot be used in place of original object in the client code.
• A decorator always inherits from the same interface/class from which object it decorates
inherits.
Proxy
• What is a Proxy?
• We need to provide a placeholder or surrogate to another object.
• Proxy acts on behalf of the object and is used for lots of rezones some of the
main reasons are:
• Protection Proxy – Control access to original object’s operations
• Remote Proxy – Provides a local representation of a remote object
• Virtual Proxy – Delays construction of original object until absolutely necessary
• Client is unaware of existence of proxy. Proxy performs its work transparently.
• Lazy loading of collections by hibernate , AOP based method level security.
RMI/Web Service stubs are examples of real life proxy usage.
Proxy
Proxy
• Implement a Proxy
• We start by implementing proxy
• Proxy must implement same interface as the real subject
• We can either create actual object later when required or ask for one in constructor.
• In method implementation of proxy we implement proxy functionality before delegating
to real object.
• How to provide client with proxies instance is decided by application. We can
provide a factory or compose client code with proxies instance.
• What we are implementing above is also called as static proxy. Java also
provides dynamic proxies.
Proxy
Proxy
• Implementation Considerations
• How proxy gets hold of the real object is depends on what purpose proxy
servers.
• For creation on demand type of proxies, actual object is created only when
proxy cant handle client request.
• Proxy itself can maintain/cache some state on behalf of real object in creation
demand use cases.
Proxy
• Design Considerations
• Proxies typically do not need to know about the actual concrete
implementation of real object.
• Proxies are great for implementing security or as stan-in of real objects which
may be a costly object that you want to defer loading.
• Proxies also make working with remote services/API easy by representing
them as regular objects and possibly handling network communication
behind the scene.
Proxy
• Examples of Proxy
• Hibernates uses a proxy to load collections of values types. If you have a
relationship in entity class mapped as a collection, marked as candidate for
lazy loading the Hibernate will provide a proxy in its place.
Proxy
• Pitfalls
• Proxies look quite similar to other patterns like decorator and adapter
patterns. It can be confusing to figure it out from the code alone for someone
not familiar with all these patterns.
Proxy
• Quiz
• Which of the following is NOT a correct use of Proxy Pattern?
• Controlling access to methods of real object.
• Providing local representation of remote objects and services.
• Delaying construction of real object until needed.
• Providing new instances via cloning.
• Which of the following is an example of usage of Proxy design pattern?
• Storing objects in an instance of java.util.ArrayList class.
• The java.lang.Runtime class implementation.
• Lazy loading of collections by Hibernate.
• The lock interface and its implementations in java
Behavioural Design Patterns
• Chain of Responsibility
• Command
• Interpreter
• Mediator
• Iterator
• Memento
• Observer
• State
• Strategy
• Template Method
• Visitor
• Null Object
Chain of Responsibility
• What is Chain of Responsibility?
• We need to avoid coupling the code which sends request to the code which
handles that request.
• Typically the code which wants some request handled calls exact method on
an exact object to process it, thus the tight coupling.
• Chain of responsibility solve this problem by giving more than one object,
chance to process the request.
• We create objects which are chained together by one object knowing
reference of object which is next in chain. We give request to first object in
chain, if it cant handle that it simply passes the request down the chain.
Chain of Responsibility
• Implement Chain of Responsibility
• We start by defining handler interface/abstract class
• Handler must define a method to accept incoming request
• Handler can define method to access successor in chain. If its an abstract class then we
can even maintain successor
• Next we implement handler in one or more concrete handlers. Concrete
handler should check if it can handle the request. If not then it should pass
request to next handler.
• We have to create our chain of objects next. We can do it in client. Typically in
real world this job will be done by some framework or initialization code
written by you.
UML
Chain of Responsibility
• Implementation Considerations
• Prefer defining handler as interface as it allows you to implement chain of
responsibility without worrying about single inheritance rule in java.
• Handlers can allow the request to propagate even if they handle the request.
Servlet filter chains allow request to flow to next filter even if they perform
some action in request.
Chain of Responsibility
• Example of a Chain of responsibility
• Probably the best example of chain of responsibility is servlet filters.
• Each filter gets a chance to handle incoming request and passes it down to
the chain once its work is done.
Chain of Responsibility
• Pitfalls
• There is no guarantee provided in the pattern that a request will be handled.
• Request can traverse whole chain and fall off at the other end without ever
being processed and we wont know it.
• It is easy to misconfigure the chain when we care connecting successors.
• There is nothing in the pattern that will let us know of any such problems.
Chain of Responsibility
• Quiz
• In Chain of Responsibility design pattern how is the request object passed
from one handler to another?
• Client code knows about all handlers in advance and calls the one by one, passing the
request object.
• Request object is actually never passed on to more than one handler.
• Java runtime takes care of calling handlers.
• Each handler knows the next one and passes request object by calling the next handler.
Chain of Responsibility
• Quiz
• Which one of the following is drawback of Chain of Responsibility design
pattern?
• A request may go unprocessed and client may not know about it.
• There is a tight coupling between client code which wants a request processed and all
handler classes.
• Handler classes need to process each and every request object and take some action
thus they are difficult to implement.
Observer
• What is Observer?
• Using observer design pattern we can notify multiple objects whenever an
object changes state.
• This design pattern is also called as publisher-subscriber.
• We are defining one-to-many dependency between objects, where many
objects are listening for state change of a single object without tightly
coupling all if them together.
• This pattern is often implemented where listener only gets notifications that
something has changed in objects state.
• Listeners query back to find out more information if needed. This makes it
more generic as different listeners may be interested in different states.
UML
Observer
• Implement Observer
• We define an interface for observer.
• Observer is usually a very simple interface and defines a method used by
“subject” to notify about state change.
• Subject can be an interface if we are expecting our observers to listen to
multiple object or else subject can be any concrete class
• Implementing subject means taking care of handling attach , detach of
observers , notifying all registered observers and providing methods to
provide state information requested by observers.
UML
Observer
• Implementation Considerations
• In some rare scenarios you may end with a circular update loop. i.e. an
update to observables state results in notification being sent to a observer
which then takes some action and that action results in state change of our
observable , triggering another notification and so on.
• An observer object can listen for changes in multiple objects. It becomes
quite easy to identify originator for the notification if subjects pass a
reference to themselves in notification to observer
Observer
• Examples of Observer
• Observer is such a useful pattern that Java comes with support for this in java
class library.
• We have java.util.Observer interface and java.util.Observable class shipped
with JDK.
Observer
• Pitfalls
• Every setter method triggering updated may be too much if we have client
setting properties one after another on our observable.
• Also each update becomes expensive as no of observers increase and we
have on or more slow observes in the list.
• If observers call back the subject to find what changed then this can add up to
quite a bit of overhead.
Observer
• Quiz
• Which of the following statements defines ideal scenario where Observer
design pattern can be used?
• Couple of objects are communicating between themselves and we want to encapsulate
this communication.
• We have a request object which needs to be processed but client does not know and
care which object is actually processing it.
• An object state needs to stored whenever it changes and we need another “sealed ”
object to store the current state.
• One or more objects are interested in knowing when specific object changes state.
Observer
• Quiz
• Select true statement from option below
• Observable is also called as a “subject” and it notifies “listeners”
• Observer is also called as a “subject” and it notifies “listeners”

More Related Content

PPTX
Gof design patterns
PPT
Unit 2-Design Patterns.ppt
PDF
Why Design Patterns Are Important In Software Engineering
PPTX
PDF
E1803023637
PPTX
Creational Design Patterns.pptx
PDF
The maze of Design Patterns & SOLID Principles
PPTX
Design Patterns
Gof design patterns
Unit 2-Design Patterns.ppt
Why Design Patterns Are Important In Software Engineering
E1803023637
Creational Design Patterns.pptx
The maze of Design Patterns & SOLID Principles
Design Patterns

Similar to design patter related ppt and presentation (20)

PPTX
OOPSDesign PPT ( introduction to opps and design (
PPT
P Training Presentation
PPTX
CREATIONAL Pattern .pptx
PPTX
Design patterns(red)
PPTX
Creational pattern 2
PPT
Design Pattern For C# Part 1
PPTX
PATTERNS02 - Creational Design Patterns
PPT
Factory Method Pattern
PPTX
Introduction to Design Patterns
PPTX
Code Like a Ninja Session 7 - Creational Design Patterns
PPT
5 Design Patterns Explained
PPTX
Software Architecture and Design Patterns Notes.pptx
PPT
PPTX
Software System Architecture-Lecture 6.pptx
PPTX
Software Patterns
PPTX
Factory Pattern
PPTX
Let us understand design pattern
PPT
Jump Start To Ooad And Design Patterns
PPS
Jump start to OOP, OOAD, and Design Pattern
PPTX
Creational pattern
OOPSDesign PPT ( introduction to opps and design (
P Training Presentation
CREATIONAL Pattern .pptx
Design patterns(red)
Creational pattern 2
Design Pattern For C# Part 1
PATTERNS02 - Creational Design Patterns
Factory Method Pattern
Introduction to Design Patterns
Code Like a Ninja Session 7 - Creational Design Patterns
5 Design Patterns Explained
Software Architecture and Design Patterns Notes.pptx
Software System Architecture-Lecture 6.pptx
Software Patterns
Factory Pattern
Let us understand design pattern
Jump Start To Ooad And Design Patterns
Jump start to OOP, OOAD, and Design Pattern
Creational pattern
Ad

More from Indu32 (12)

PPTX
jdbcppt.pptx , jdbc ppt jdbc ppt jdbc ppt jdbc ppt jdbc ppt jdbc ppt jdbc ppt
PDF
java-basics-1.pdf jfjf hjghjgkj df jfjf hjghjgkj df jfjf hjghjgkj df jfjf hjg...
PPTX
Introduction to MySQL commands mysql presentation 22.pptx
PDF
unit8_jdbc.pdf mysql and java jdbc connection
PPTX
css front end development , designing web page
PPTX
CSS presentation for beginners where they can understand easily
PPTX
html webpage development different tags used
PPTX
Web development ppt used to design web applocation
PPTX
In the given example only one object will be created. Firstly JVM will not fi...
PPT
In this page, we will learn about the basics of OOPs. Object-Oriented Program...
PPT
In this page, we will learn about the basics of OOPs. Object-Oriented Program...
PPT
java basic ppt introduction, The Java language is known for its robustness, s...
jdbcppt.pptx , jdbc ppt jdbc ppt jdbc ppt jdbc ppt jdbc ppt jdbc ppt jdbc ppt
java-basics-1.pdf jfjf hjghjgkj df jfjf hjghjgkj df jfjf hjghjgkj df jfjf hjg...
Introduction to MySQL commands mysql presentation 22.pptx
unit8_jdbc.pdf mysql and java jdbc connection
css front end development , designing web page
CSS presentation for beginners where they can understand easily
html webpage development different tags used
Web development ppt used to design web applocation
In the given example only one object will be created. Firstly JVM will not fi...
In this page, we will learn about the basics of OOPs. Object-Oriented Program...
In this page, we will learn about the basics of OOPs. Object-Oriented Program...
java basic ppt introduction, The Java language is known for its robustness, s...
Ad

Recently uploaded (20)

PDF
Supply Chain Operations Speaking Notes -ICLT Program
PDF
01-Introduction-to-Information-Management.pdf
PDF
Basic Mud Logging Guide for educational purpose
PDF
ANTIBIOTICS.pptx.pdf………………… xxxxxxxxxxxxx
PPTX
Introduction_to_Human_Anatomy_and_Physiology_for_B.Pharm.pptx
PDF
O7-L3 Supply Chain Operations - ICLT Program
PDF
O5-L3 Freight Transport Ops (International) V1.pdf
PPTX
Pharmacology of Heart Failure /Pharmacotherapy of CHF
PDF
Computing-Curriculum for Schools in Ghana
PDF
Chapter 2 Heredity, Prenatal Development, and Birth.pdf
PPTX
Final Presentation General Medicine 03-08-2024.pptx
PDF
STATICS OF THE RIGID BODIES Hibbelers.pdf
PDF
TR - Agricultural Crops Production NC III.pdf
PPTX
Pharma ospi slides which help in ospi learning
PPTX
master seminar digital applications in india
PDF
3rd Neelam Sanjeevareddy Memorial Lecture.pdf
PDF
Microbial disease of the cardiovascular and lymphatic systems
PDF
102 student loan defaulters named and shamed – Is someone you know on the list?
PPTX
Microbial diseases, their pathogenesis and prophylaxis
PPTX
school management -TNTEU- B.Ed., Semester II Unit 1.pptx
Supply Chain Operations Speaking Notes -ICLT Program
01-Introduction-to-Information-Management.pdf
Basic Mud Logging Guide for educational purpose
ANTIBIOTICS.pptx.pdf………………… xxxxxxxxxxxxx
Introduction_to_Human_Anatomy_and_Physiology_for_B.Pharm.pptx
O7-L3 Supply Chain Operations - ICLT Program
O5-L3 Freight Transport Ops (International) V1.pdf
Pharmacology of Heart Failure /Pharmacotherapy of CHF
Computing-Curriculum for Schools in Ghana
Chapter 2 Heredity, Prenatal Development, and Birth.pdf
Final Presentation General Medicine 03-08-2024.pptx
STATICS OF THE RIGID BODIES Hibbelers.pdf
TR - Agricultural Crops Production NC III.pdf
Pharma ospi slides which help in ospi learning
master seminar digital applications in india
3rd Neelam Sanjeevareddy Memorial Lecture.pdf
Microbial disease of the cardiovascular and lymphatic systems
102 student loan defaulters named and shamed – Is someone you know on the list?
Microbial diseases, their pathogenesis and prophylaxis
school management -TNTEU- B.Ed., Semester II Unit 1.pptx

design patter related ppt and presentation

  • 2. SOLID Principles • Single Responsibility Principle • Open Closed Principle • Liskov Substitution Principle • Interface Segregation Principle • Dependency Inversion Principle
  • 3. Single Responsibility Principle • There should never be more than one reason for a class to change • The class provides a very focused functionality. • It addresses a specific concern of our desired functionality.
  • 4. Open Closed Principle • Software entities(Class , Modules, Methods) should be open for extension but closed for modification. • Open for extension : Extend existing behaviour(Create new class which derived from base and override methods). • Closed for modification : Existing code remains unchanged(Avoid modification in base classes).
  • 5. Liskov Substitution Principle • Object of a superclass shall be replaceable with objects of its subclasses without breaking the application.
  • 6. Interface Segregation Principle • Clients should not be forced to depend upon interfaces that they do not use. • This is also known as interface pollutions(Large and unrelated methods) • Classes have empty method implementations • Method implementations return null or default/dummy values. • Write Highly Cohesive Interfaces.
  • 7. Dependency Inversion Principle • Part 1 : High level modules should not depend upon low level modules. Both should depend upon abstractions. • Part 2 : Abstractions should not depend upon details. Details should depend upon abstractions.
  • 8. Design Pattern • Creational Design Pattern • Creational patterns deal with the process of creation of objects of classes. • Structural Design Pattern • Structural patterns deal with how classes and objects are arranged or composed. • Behavioural Design Pattern • Behavioural Design Patterns describe how classes and objects interact and communicate with each other.
  • 9. Creational Design Pattern • Builder • Simple Factory • Factory Method • Prototype • Singleton • Abstract Factory • Object Pool
  • 10. Builder Pattern • What problem builder design pattern solves? • Class constructor requires a lots of information • Having a lots of arguments in constructor parameter is not a good practice. • It also creates the confusion if the constructor parameter has same datatypes. • Sometimes constructor also require some other class object as parameter. //Product instances are immutable class Product { public Proudct(int weight, double price, int shipVolume, int shipCode) { // variable initialization } // other code }
  • 11. Builder Pattern • Builder pattern make it easy to use such constructors so that we can create objects of this class. • It also help us avoid writing such constructors in first place and still have our objects immutable.
  • 12. Builder Pattern • What is a Builder? • We have a complex process to construct an object involving multiple steps, then builder design pattern can help us. • In builder we remove the logic related to object construction from “Client” code and abstract it in separate classes
  • 13. UML
  • 14. UML
  • 15. UML
  • 16. UML
  • 17. UML
  • 18. Implement a Builder • We start by creating a builder • Identify the parts of the product and provide methods to create those parts • It should provide a method to assemble or build the product/object • It must provide a way/method to get fully built object out. Optionally builder can keep reference to an product it has built the same can be returned again in future. • A director can be a separate class or client can play the role of director.
  • 20. Simple Factory • What problem simply factory solves? • Multiple types can be instantiated, and the choice is based on simple criteria if(key.equalsIgnoreCase("pudding")) { // create pudding object } else if (key.equalsIgnoreCase("cake")) { // create cake object }
  • 21. Simple Factory • What is a Simple Factory? • Here we simply move the instantiation logic to a separate class and most commonly to a static method of this class. • Some do not consider simple factory to be a “design pattern” as its simply a method that encapsulates the object instantiation. • Nothing complex goes on in that method. • We are studying simple factory as it is often confused with “factory method” pattern • Typically, we want to do this if we have more than one option when instantiating object and a simple logic is used to choose correct class.
  • 23. Simple Factory • Implement a Simple Factory • We start by creating a separate class for our simple factory • Add method with returns desired object instance. • This method is typically static and will accept some argument to decide which class to instantiate. • You can also provide additional arguments which will be used to instantiate objects.
  • 24. Simple Factory • Implementation Considerations • Simple factory can be just a method in existing class. Adding a separate class however allows other parts of your code to use simple factory more easily. • Simple factory itself doesn’t need any state tracking so its best to keep this as a static method. • Simple factory will in turn may use other design pattern like builder to construct objects. • In case you want o specialized your simple factory in sub classes , you need factory method design pattern instead.
  • 25. Simple Factory • The java.text.NumberFormat class has getInstance method, which is an example of simple factory.
  • 26. Simple Factory Simple Factory • We simply move our instantiation logic away from client code. Typically, in a static method. • Simple factory knows about all classes whose object it can create. Factory Method • Factory method is more useful when you want to delegate object creation to subclasses. • In Factory method we don’t know in advance about all products subclasses.
  • 27. Simple Factory • Pitfalls • The criteria used by simple factory to decide which object to instantiate can get more convoluted/complex over time. • If you find yourself in such situation then use factory method design pattern.
  • 28. Simple Factory • Quiz • Select correct/true statements regarding the simple factory pattern from following statements. • A simple factory assembles objects one part at a time. • A simple factory allows to maintain single instance of a class in entire application. • A simple factory can instantiate an object based on simple criteria. • A simple factory saves JVM memory by pooling the objects. • Select the benefits of implementing simple factory in a separate class. • It allows simple factory to use inheritance and specialized object creation. • It allows to reuses the simple factory by other classes without importing unrelated classes.
  • 29. Factory Method • What is a factory method? • We want to move the object creation logic from our code to separate class. • We use this pattern when we do not know in advance which class we may need to instantiate beforehand. • Also to allow new classes to be added to system and handle their creation without affecting client code. • We let subclasses decide which object to instantiate by overriding the factory method.
  • 30. UML
  • 31. UML
  • 32. Factory Method • Implement a Factory Method • We start by creating a class for our creator • Creator itself can be concreate if it can provide a default object or it can be abstract. • Implementations will override the method and return object.
  • 33. UML
  • 34. Factory Method • Implementation Considerations • The creator can be a concrete class and provide a default implementation for the factory method. In such cases you will create some default object in base creator. • You can use the simple factory way of accepting additional arguments to choose between different object types. Subclasses the override factory method to selectively create different object for some criteria.
  • 35. Factory Method • Design Considerations • Creator hierarchy in factory method pattern reflets the product hierarchy. • We typically end up with a concrete creator per object type. • Template method design pattern often makes use of factory method. • Another creational design pattern called ”abstract factory” makes use of factory method pattern.
  • 36. Factory Method • Examples of a Factory Method • The java.util.Collection(or java.util.AbstractCollection) has an abstract method called iterator(). This method is an example of factory method.
  • 37. Factory Method • Pitfalls • More complex to implement. More classes are involved and need unit testing. • You have to start with Factory method design pattern from the beginning. It is not easy to refactor existing code into factory method pattern. • Sometimes this pattern forces you to subclass just to create appropriate instance.
  • 38. Factory Method • Quiz • Which statement describles the difference between “Factory Method” and “Simple Factory” patterns? • Factory method uses inheritance to specialize object creation and simple factory don’t use inheritance. • Factory method is always static method in a final class while simple factory always uses non-static method. • To support creation of a new type of object we need to modify existing factory method pattern implementation while in simple factory pattern we add a new child class which creates the new object. • Factory Method pattern needs less number of classes to implement the Simple Factory method pattern when working with same product hierarchy.
  • 39. Factory Method • Quiz • What is a drawback of factory method pattern? • We need to modify existing code of factory method pattern whenever a new product class is added to system • We often end up creating child classes just to instantiate a new object resulting in large number of classes which need unit testing.
  • 40. Prototype • What is a Prototype? • We have a complex object that is costly to create. To create more instances of such class, We use and existing instance as our prototype. • Prototype will allow us to make copies of existing objects and save us from having to recreate objects from scratch.
  • 41. UML
  • 42. UML
  • 43. Prototype • Implement a Prototype • We start by creating a class which will be a prototype • The class must implement cloneable interface • Class should override clone method and return copy of itself. • The method should declare CloneNotSupportedException in thows clause to give subclasses chance to decide on whether to support cloning. • Clone method implementation should consider the deep and shallow copy and choose whichever is applicable.
  • 44. Prototype • Implementation Considerations • Pay attention to the deep copy and shallow copy of references. • Immutable fields on clones save the trouble of deep copy. • Make sure to reset the mutable state of objects before returning the prototype. It’s a good idea to implement this in method to allow subclasses to initialize themselves. • Clone() method is protected in Object class and must be overridden to public to be callable from outside the class. • Cloneable is a marker interface
  • 45. Prototype • Design Considerations • Prototypes are useful when you have large objects where majority of state is unchanged between instances and you can easily identify that state. • Prototypes are useful when working with Composits and Decorator Patterns
  • 46. Prototype • Actually the Object.clone() method is an example of a prototype!
  • 47. Prototype Prototype • We return a copy of an instance, meaning we get a new instance • Some or even all of the state of instances created with prototypes can be different Singleton • We return same instance every time. • Since it’s the same object that is returned state is always the same.
  • 48. Prototype • Pitfalls • Usability depends upon the number of properties in state that are immutable or can be shallow copied. • An object where state is comprised of large number of mutable objects is complicated to clone. • In java the default clone operation will only perform the shallow copy so if you need a deep copy you must implement it. • Subclasses may not be able to support clone and so the code becomes complicated as you have to code for situations where an implementations my not support clone.
  • 49. Prototype • Quiz • Which of the following statement is true with regards to Prototype design pattern? • Prototype allows only one instance of the class to be created in entire application. • An object created with prototype pattern can never be garbage collected. • Prototype class must be declared as final to prevent inheritance. • Prototype pattern copies an existing object to create separate new object • Select the true statement from the following statements. • The clone() method provided in the Object class performs deep copy of the object. • The clone() method from Object needs to be overridden to make it public. • The clone() method is declared in Cloneable interface. • We can clone objects of any class in java.
  • 50. Prototype • Quiz • Why we have to implement Cloneable interface in Prototype design pattern • It is not mandatory and just good practice to implement cloneable! • This interface adds the clone() method which is used to clone the object. • If cloneable interface is not implemented then clone method throws exception. • Cloneable needs to be implemented otherwise code dose not compile.
  • 51. Singleton • What is a Singleton? • A singleton class has only one instance, accessible globally through a single point. • Main problem this pattern solves is to ensure that only a single instance of this class exists. • Any state you add in your singleton becomes apart of “global state” of your application.
  • 52. Singleton • Implement a Singleton • Controlling instance creation • Class constructor(s) must be not be accessible globally • Subclassing /inheritance must not be allowed • Keeping track of instance • Class itself is a good place to track the instance • Giving access to the singleton instance • A public static method is good choice • Can expose instance as final public static fields but it wont work for all singleton implementations.
  • 53. Singleton • Two options for implementing a singleton • Early initialization – Eager Singleton • Create singleton as soon as class is loaded • Lazy initialization – Lazy Singleton • Singleton is created when it is first required
  • 54. Singleton • Implementation Considerations • Early/Eager initialization is the simplest and preferred way. • The classic singleton pattern implementation uses double check locking and volatile field. • The lazy initialization holder idiom provides best of both worlds, you don’t deal with synchronization issues directly and is easy to implement.
  • 55. Singleton • Design Considerations • Singleton creation does not need any parameters. If you find yourself in need of support for constructor arguments, you need a simple factory or factory method pattern instead.
  • 56. Singleton • Example of a Singleton Pattern • Java.lang.Runtime class in standard Java API is a singleton.
  • 57. Singleton • Singleton pattern can deceive you about true dependencies! Since you are globally accessible its easy to miss dependencies. • They are hard to unit test. You cannot easily mock the instance that is returned. • Most common way to implement singletons in Java is through static variables and they are held per class loader and not per JVM. So they may not be truly singleton.
  • 58. Singleton • Quiz • What is Eager singleton? • In eager singleton implementation the singleton instance is created as soon the singleton class is referenced. • In eager singleton implementation the singleton instance is created when some code calls getInstance() method. • In eager singleton implementation the singleton instance is created as soon as JVM process starts. • In eager singleton implementation the singleton instance is created when an instance method is called on singleton reference.
  • 59. Singleton • Quiz • What is double check locking that is used by lazy singleton implementation? • Double check locking means we use two synchronization blocks, one inside another. We also use volatile keyword to declare reference. • We check twice for the singleton reference to be null, once before synchronization block and then inside the synchronization block and we have to make sure the reference is volatile. • Two separate locks are declared in the singleton class and we have to ensure both locks are locked to create singleton instance. • We call getInstacen() method twice and check the return value.
  • 60. Structural Design Pattern • Adapter • Bridge • Decorator • Composite • Façade • Flyweight • Proxy
  • 61. Adapter(aka Wrapper) • What is Adapter? • We have an existing object which provides the functionality that client needs. But client cant use this object because it expects and object with different interface. • Using adapter design pattern we make this existing object work with client by adapting the object to client’s expected interface. • This pattern is also called as wrapper as its ”wraps” existing object.
  • 62. UML – Class Adapter
  • 63. UML – Class Adapter
  • 64. UML – Object Adapter
  • 65. UML – Object Adapter
  • 66. Adapter • Implement an Adapter • We start by creating a class for Adapter • Adapter must implement the interface expected by client. • First we are going to try out a class adapter by also extending from our existing class. • In the class adapter implementation we are simply going to forward the method to another method inherited from adaptee. • Next for object adapter , we are only going to implement target interface and accept adaptee as constructor argument in adapter i.e. make use of composition. • An object adapter should take adaptee as an argument in constructor or as less preferred solution, you can instantiate it in the constructor thus tightly coupling with a specific adaptee
  • 67. Example UML – Class Adapter
  • 68. Example : UML (Object Adapter)
  • 69. Adapter • Implementation Considerations • How much work the adapter does depends upon the differences between target interface and object being adapted. • If method arguments are same or similar adapter has very less work to do.
  • 70. Adapter • In java a “class adapter” may not be possible if both target and adaptee are concrete classes. In such cases the object adapter is the only solution. Also since there is not private inheritance in java its better to stick with object adapter. • A class adapter is also called as a two way adapter, since it can stand in for both the target interface and for the adaptee. That is we can use object of adapter where either target interface is expected as well as and adaptee object is expected.
  • 71. Adapter • Examples of an Adapter • The java.io.InputStreamReader and OutputStreamWriter classes
  • 72. Adapter • Pitfalls • Using target interface and adaptee class to extend our adapter we can create a class adapter in java. • However it create an object which exposes unrelated methods in parts of your code, polluting it. • Avoid class adapters.
  • 73. Adapter • Quiz • Which one of the following scenarios is most suitable for using Adapter design pattern? • We want to add new functionality to a class without modifying original code. • We have existing object the provide needed functionality but client code needs expects different interface. • We want to hide our real object for client. • When we want to intercept method calls for logging and authantication.
  • 74. Adapter • Quiz • Which one of the following is not NOT a type of adapter in Adapter Design Pattern? • Class Adapter • Java Adapter • Object Adapter
  • 75. Decorator • What is Decorator? • When we want to enhance behaviour of our existing object dynamically as and when required then we can use decorator design pattern. • Decorator wraps an object within itself and provides same interface as the wrapped object. So the client of original object doesn’t need to change. • A decorator provides alternative to subclassing for extending functionality of existing classes.
  • 77. Decorator • Implement a Decorator • We start with our component • Component defines interface needed or already used by client. • Concrete component implements the component. • We define our decorator. Decorator implements components and also needs reference to concrete component. • In decorator methods we provide additional behaviour on top the provided by concrete component instance. • Decorator can be abstract as well & depend on subclasses to provide functionality.
  • 79. Decorator • Implementation Considerations • Since we have decorators and concrete class extending from common component , avoid large state in this base class as decorators may not need all that state. • Pay attention to equals and hashCode methods of decorator. When using decorators, you have to decide if decorated object is equal to same instance without decorator. • Decorator supports recursive composition and so this pattern lends itself to creation of lots of small objects that add “just a little bit” functionality. Code using these objects becomes difficult to debug.
  • 80. Decorator • Design Considerations • Decorators are more flexible and powerful than inheritance. • Inheritance is static by definition but decorators allow you to dynamically compose behaviour using objects at runtime. • Decorators should act like additional skin over your object. They should add helpful small behaviours to objects original behaviour. Do not change the meaning of operations.
  • 81. Decorator • Example of Decorator • Classes in java I.O packages are great examples of decorator pattern. • For example java.io.BufferedOutputStream class decorates any java.io.OutputStream object and adds buffering to file writing operations.
  • 82. Decorator • Pitfalls • Often result in large number of classes being added to system, Where each class adds small amount of functionality. • Sometimes new comers will start using it as a replacement of inheritance in every scenario. Think of decorators as a thin skin existing objects.
  • 83. Decorator • Quiz • What is the fundamental purpose behind using Decorator design pattern? • It allows us to adapt existing object to a new interface expected by the client code. • Add new functionality on top of what is provided by existing object. • To completely change the functionality of existing object. • Provide decorative formatting to objects textual representation. • Decorators allows recursive composition. What exactly dose “Recursive composition” means in this context? • It means , a decorator can be composed with/wrap another decorator written for same object which in turn can also wrap another decorator and so on. • All decorator methods can be called recursively. • The decorators call recursive methods on the original object. • Its simply a single decorator containing the original object via composition. We cant compose a decorator with another decorator.
  • 84. Decorator • Quiz • Select the true/correct statements from below. • A decorator changes the interface of the object which it decorates. • A single decorator instead can be decorate multiple objects at the same time. • A decorator cannot be used in place of original object in the client code. • A decorator always inherits from the same interface/class from which object it decorates inherits.
  • 85. Proxy • What is a Proxy? • We need to provide a placeholder or surrogate to another object. • Proxy acts on behalf of the object and is used for lots of rezones some of the main reasons are: • Protection Proxy – Control access to original object’s operations • Remote Proxy – Provides a local representation of a remote object • Virtual Proxy – Delays construction of original object until absolutely necessary • Client is unaware of existence of proxy. Proxy performs its work transparently. • Lazy loading of collections by hibernate , AOP based method level security. RMI/Web Service stubs are examples of real life proxy usage.
  • 86. Proxy
  • 87. Proxy • Implement a Proxy • We start by implementing proxy • Proxy must implement same interface as the real subject • We can either create actual object later when required or ask for one in constructor. • In method implementation of proxy we implement proxy functionality before delegating to real object. • How to provide client with proxies instance is decided by application. We can provide a factory or compose client code with proxies instance. • What we are implementing above is also called as static proxy. Java also provides dynamic proxies.
  • 88. Proxy
  • 89. Proxy • Implementation Considerations • How proxy gets hold of the real object is depends on what purpose proxy servers. • For creation on demand type of proxies, actual object is created only when proxy cant handle client request. • Proxy itself can maintain/cache some state on behalf of real object in creation demand use cases.
  • 90. Proxy • Design Considerations • Proxies typically do not need to know about the actual concrete implementation of real object. • Proxies are great for implementing security or as stan-in of real objects which may be a costly object that you want to defer loading. • Proxies also make working with remote services/API easy by representing them as regular objects and possibly handling network communication behind the scene.
  • 91. Proxy • Examples of Proxy • Hibernates uses a proxy to load collections of values types. If you have a relationship in entity class mapped as a collection, marked as candidate for lazy loading the Hibernate will provide a proxy in its place.
  • 92. Proxy • Pitfalls • Proxies look quite similar to other patterns like decorator and adapter patterns. It can be confusing to figure it out from the code alone for someone not familiar with all these patterns.
  • 93. Proxy • Quiz • Which of the following is NOT a correct use of Proxy Pattern? • Controlling access to methods of real object. • Providing local representation of remote objects and services. • Delaying construction of real object until needed. • Providing new instances via cloning. • Which of the following is an example of usage of Proxy design pattern? • Storing objects in an instance of java.util.ArrayList class. • The java.lang.Runtime class implementation. • Lazy loading of collections by Hibernate. • The lock interface and its implementations in java
  • 94. Behavioural Design Patterns • Chain of Responsibility • Command • Interpreter • Mediator • Iterator • Memento • Observer • State • Strategy • Template Method • Visitor • Null Object
  • 95. Chain of Responsibility • What is Chain of Responsibility? • We need to avoid coupling the code which sends request to the code which handles that request. • Typically the code which wants some request handled calls exact method on an exact object to process it, thus the tight coupling. • Chain of responsibility solve this problem by giving more than one object, chance to process the request. • We create objects which are chained together by one object knowing reference of object which is next in chain. We give request to first object in chain, if it cant handle that it simply passes the request down the chain.
  • 96. Chain of Responsibility • Implement Chain of Responsibility • We start by defining handler interface/abstract class • Handler must define a method to accept incoming request • Handler can define method to access successor in chain. If its an abstract class then we can even maintain successor • Next we implement handler in one or more concrete handlers. Concrete handler should check if it can handle the request. If not then it should pass request to next handler. • We have to create our chain of objects next. We can do it in client. Typically in real world this job will be done by some framework or initialization code written by you.
  • 97. UML
  • 98. Chain of Responsibility • Implementation Considerations • Prefer defining handler as interface as it allows you to implement chain of responsibility without worrying about single inheritance rule in java. • Handlers can allow the request to propagate even if they handle the request. Servlet filter chains allow request to flow to next filter even if they perform some action in request.
  • 99. Chain of Responsibility • Example of a Chain of responsibility • Probably the best example of chain of responsibility is servlet filters. • Each filter gets a chance to handle incoming request and passes it down to the chain once its work is done.
  • 100. Chain of Responsibility • Pitfalls • There is no guarantee provided in the pattern that a request will be handled. • Request can traverse whole chain and fall off at the other end without ever being processed and we wont know it. • It is easy to misconfigure the chain when we care connecting successors. • There is nothing in the pattern that will let us know of any such problems.
  • 101. Chain of Responsibility • Quiz • In Chain of Responsibility design pattern how is the request object passed from one handler to another? • Client code knows about all handlers in advance and calls the one by one, passing the request object. • Request object is actually never passed on to more than one handler. • Java runtime takes care of calling handlers. • Each handler knows the next one and passes request object by calling the next handler.
  • 102. Chain of Responsibility • Quiz • Which one of the following is drawback of Chain of Responsibility design pattern? • A request may go unprocessed and client may not know about it. • There is a tight coupling between client code which wants a request processed and all handler classes. • Handler classes need to process each and every request object and take some action thus they are difficult to implement.
  • 103. Observer • What is Observer? • Using observer design pattern we can notify multiple objects whenever an object changes state. • This design pattern is also called as publisher-subscriber. • We are defining one-to-many dependency between objects, where many objects are listening for state change of a single object without tightly coupling all if them together. • This pattern is often implemented where listener only gets notifications that something has changed in objects state. • Listeners query back to find out more information if needed. This makes it more generic as different listeners may be interested in different states.
  • 104. UML
  • 105. Observer • Implement Observer • We define an interface for observer. • Observer is usually a very simple interface and defines a method used by “subject” to notify about state change. • Subject can be an interface if we are expecting our observers to listen to multiple object or else subject can be any concrete class • Implementing subject means taking care of handling attach , detach of observers , notifying all registered observers and providing methods to provide state information requested by observers.
  • 106. UML
  • 107. Observer • Implementation Considerations • In some rare scenarios you may end with a circular update loop. i.e. an update to observables state results in notification being sent to a observer which then takes some action and that action results in state change of our observable , triggering another notification and so on. • An observer object can listen for changes in multiple objects. It becomes quite easy to identify originator for the notification if subjects pass a reference to themselves in notification to observer
  • 108. Observer • Examples of Observer • Observer is such a useful pattern that Java comes with support for this in java class library. • We have java.util.Observer interface and java.util.Observable class shipped with JDK.
  • 109. Observer • Pitfalls • Every setter method triggering updated may be too much if we have client setting properties one after another on our observable. • Also each update becomes expensive as no of observers increase and we have on or more slow observes in the list. • If observers call back the subject to find what changed then this can add up to quite a bit of overhead.
  • 110. Observer • Quiz • Which of the following statements defines ideal scenario where Observer design pattern can be used? • Couple of objects are communicating between themselves and we want to encapsulate this communication. • We have a request object which needs to be processed but client does not know and care which object is actually processing it. • An object state needs to stored whenever it changes and we need another “sealed ” object to store the current state. • One or more objects are interested in knowing when specific object changes state.
  • 111. Observer • Quiz • Select true statement from option below • Observable is also called as a “subject” and it notifies “listeners” • Observer is also called as a “subject” and it notifies “listeners”