SlideShare une entreprise Scribd logo
1  sur  26
Télécharger pour lire hors ligne
Design Patterns
Factory
Flyweight
Singleton
Observer
Proxy
Decorator
What Are Design Patterns?
A solution to a language
independent OO Problem.
If the solution is a
reoccurring over time, it
becomes a “Pattern”.
.net
Java
C++
C#
VB.net
Factory Pattern
Definition
The Factory pattern provides a way to use an instance as a object
factory. The factory can return an instance of one of several possible
classes (in a subclass hierarchy), depending on the data provided to
it.
Where to use
1) When a class can't anticipate which kind of class of object it must
create.
2) You want to localize the knowledge of which class gets created.
3) When you have classes that is derived from the same subclasses,
or they may in fact be unrelated classes that just share the same
interface. Either way, the methods in these class instances are the
same and can be used interchangeably.
4) When you want to insulate the client from the actual type that is
being instantiated.
Factory PatternClass Diagram
Factory Patternpublic abstract class Product {
public void writeName(String name) {
System.out.println("My name is "+name);
}
}
public class ProductA extends Product { }
public class ProductB extends Product {
public void writeName(String name) {
StringBuilder tempName = new StringBuilder().append(name);
System.out.println("My reversed name is" + tempName.reverse());
}
}
public class ProductFactory {
public Product createProduct(String type) {
if(type.equals("B"))
return new ProductB();
else
return new ProductA();
}
}
ProductFactory pf = new ProductFactory();
Product prod;
prod = pf.createProduct("A");
prod.writeName("John Doe");
prod = pf.createProduct("B");
prod.writeName("John Doe");
Connection, Statement, ResultSet
Proxy Pattern
DefinitionDefinition
A Proxy is a structural pattern that provides a stand-in for
another object in order to control access to it.
Where to useWhere to use
1) When the creation of one object is relatively expensive it can be a
good idea to replace it with a proxy that can make sure that
instantiation of the expensive object is kept to a minimum.
2) Proxy pattern implementation allows for login and authority
checking before one reaches the actual object that's requested.
3) Can provide a local representation for an object in a remote
location.
Proxy PatternClass Diagram
Proxy Patterninterface IExploded {
public void pumpPetrol(String arg);
}
class ProxyExploded implements IExploded{
public void pumpPetrol(String arg){
System.out.println("Pumping. ");
}
}
public class Pattern_Proxy implements IExploded
{
StringBuffer strbuf = new StringBuffer();
public void pumpPetrol(String arg){
strbuf.append(arg);
System.out.println("Pumping. ");
if(strbuf.length() >70){
explosion2(); strbuf.delete(0, strbuf.length()); System.exit(0);
}else if(strbuf.length()>50){
explosion1();
}
}
public void explosion1(){ System.out.println("System is about to Explode"); }
public void explosion2(){
System.out.println("System has exploded... Kaboom!!.. rn”+
”To Much Petrol.."+strbuf.length()+" L");
}
}
public static void main(String arg[])
{
IExploded prox = new Pattern_Proxy();
for(int y=0; y<50; y++){
prox.pumpPetrol("Petrol.");
}
}
Singleton Pattern
Definition
The Singleton pattern provides the possibility to control the
number of instances (mostly one) that are allowed to be
made. We also receive a global point of access to it (them).
Where to use
When only one instance or a specific number of instances of
a class are allowed. Facade objects are often Singletons
because only one Facade object is required.
Benefits
•Controlled access to unique instance.
•Reduced name space.
•Allows refinement of operations and representations.
Class Diagram
Singleton Pattern
Singleton Pattern
public class MapLogger
{
private static MapLogger mapper=null;
// Prevent clients from using the constructor
private MapLogger() { /* Nothing Here :-) */ }
//Control the accessible (allowed) instances
public static MapLogger getMapLogger() {
if (mapper == null) {
mapper = new MapLogger();
}
return mapper;
}
public synchronized void put(String key, String val)
{
// Write to Map/Hashtable...
}
}
Flyweight Pattern
Definition
The Flyweight pattern provides a mechanism by which you can
avoid creating a large number of 'expensive' objects and instead
reuse existing instances to represent new ones.
Where to use
1) When there is a very large number of objects that may not fit in
memory.
2) When most of an objects state can be stored on disk or calculated
at Runtime.
3) When there are groups of objects that share state.
4) When the remaining state can be factored into a much smaller
number of objects with shared state.
Benefits
Reduce the number of objects created, decrease memory footprint
and increase performance.
Flyweight Pattern
Flyweight Patternclass Godzilla {
private int row;
public Godzilla( int theRow ) {
row = theRow;
System.out.println( "ctor: " + row );
}
void report( int theCol ) {
System.out.print( " " + row + theCol );
}
} class Factory {
private Godzilla[] pool;
public Factory( int maxRows ) {
pool = new Godzilla[maxRows];
}
public Godzilla getFlyweight( int theRow ) {
if (pool[theRow] == null)
pool[theRow] = new Godzilla( theRow );
return pool[theRow];
}
}
public class FlyweightDemo {
public static final int ROWS = 6, COLS = 10;
public static void main( String[] args ) {
Factory theFactory = new Factory( ROWS );
for (int i=0; i < ROWS; i++) {
for (int j=0; j < COLS; j++)
theFactory.getFlyweight( i ).report( j );
System.out.println();
} } }
Observer Pattern
Definition
Proxy pattern is a behavioral pattern. It defines a one-to-many
dependency between objects, so that when one object changes its
state, all its dependent objects are notified and updated.
Where to use
1) When state changes of a one object must be reflected in other
objects without depending on the state changing process of the object
(reduce the coupling between the objects).
Observer Pattern
Observer Pattern
public class WeatherStation extends Observable implements Runnable {
public void run() {
String report = this.getCurrentReport();
notifyObservers( report );
}
}
public class WeatherObserver implements Observer {
private String response;
public void update (Observable obj, Object arg) {
response = (String)arg;
}
}
Observer Pattern
public class WeatherClient {
public static void main(String args[]) {
// create a WheatherStation instance
final WeatherStation station = new WeatherStation();
// create an observer
final WeatherObserver weatherObserver = new WeatherObserver();
// subscribe the observer to the event source
station.addObserver( weatherObserver );
// starts the event thread
Thread thread = new Thread(station);
thread.start();
}
}
Decorator Pattern
Definition
Decorator pattern is a structural pattern. Intent of the pattern is to add
additional responsibilities dynamically to an object.
Where to use
1) When you want the responsibilities added to or removed from an
object at runtime.
2) When using inheritance results in a large number of subclasses.
Decorator Pattern
Decorator Pattern
// The Coffee Interface defines the functionality of Coffee implemented by
decorator
public interface Coffee {
// returns the cost of the coffee
public double getCost();
// returns the ingredients of the coffee
public String getIngredients();
}
// implementation of a simple coffee without any extra ingredients
public class SimpleCoffee implements Coffee {
public double getCost() {
return 1;
}
public String getIngredients() {
return "Coffee";
}
}
Decorator Pattern
// abstract decorator class - note that it implements Coffee interface
abstract public class CoffeeDecorator implements Coffee {
protected final Coffee decoratedCoffee;
protected String ingredientSeparator = ", ";
public CoffeeDecorator(Coffee decoratedCoffee) {
this.decoratedCoffee = decoratedCoffee;
}
public double getCost() {
// implementing methods of the interface
return decoratedCoffee.getCost();
}
public String getIngredients() {
return decoratedCoffee.getIngredients();
}
}
Decorator Pattern
// Decorator Milk that mixes milk with coffee
// note it extends CoffeeDecorator
public class Milk extends CoffeeDecorator {
public Milk(Coffee decoratedCoffee) {
super(decoratedCoffee);
}
public double getCost() {
// overriding methods defined in the abstract superclass
return super.getCost() + 0.5;
}
public String getIngredients() {
return super.getIngredients() + ingredientSeparator + "Milk";
}
}
Decorator Pattern
public class Whip extends CoffeeDecorator {
public Whip(Coffee decoratedCoffee) {
super(decoratedCoffee);
}
public double getCost() {
return super.getCost() + 0.7;
}
public String getIngredients() {
return super.getIngredients() + ingredientSeparator + "Whip";
}
}
Decorator Pattern
public class CoffeMaker {
public static void main(String[] args) {
Coffee c = new SimpleCoffee();
System.out.println("Cost: " + c.getCost() + "; Ingredients: " + c.getIngredients());
c = new Milk(c);
System.out.println("Cost: " + c.getCost() + "; Ingredients: " + c.getIngredients());
}
}
Decorator Pattern
public class Whip extends CoffeeDecorator {
public Whip(Coffee decoratedCoffee) {
super(decoratedCoffee);
}
public double getCost() {
return super.getCost() + 0.7;
}
public String getIngredients() {
return super.getIngredients() + ingredientSeparator + "Whip";
}
}

Contenu connexe

Tendances

ADF Bindings & Data Controls
ADF Bindings & Data ControlsADF Bindings & Data Controls
ADF Bindings & Data ControlsRohan Walia
 
Hexagonal architecture with Spring Boot
Hexagonal architecture with Spring BootHexagonal architecture with Spring Boot
Hexagonal architecture with Spring BootMikalai Alimenkou
 
AWS SAM으로 서버리스 아키텍쳐 운영하기 - 이재면(마이뮤직테이스트) :: AWS Community Day 2020
AWS SAM으로 서버리스 아키텍쳐 운영하기 - 이재면(마이뮤직테이스트) :: AWS Community Day 2020 AWS SAM으로 서버리스 아키텍쳐 운영하기 - 이재면(마이뮤직테이스트) :: AWS Community Day 2020
AWS SAM으로 서버리스 아키텍쳐 운영하기 - 이재면(마이뮤직테이스트) :: AWS Community Day 2020 AWSKRUG - AWS한국사용자모임
 
Understanding Reactive Programming
Understanding Reactive ProgrammingUnderstanding Reactive Programming
Understanding Reactive ProgrammingAndres Almiray
 
Spring Framework - AOP
Spring Framework - AOPSpring Framework - AOP
Spring Framework - AOPDzmitry Naskou
 
Spring Framework - MVC
Spring Framework - MVCSpring Framework - MVC
Spring Framework - MVCDzmitry Naskou
 
Domain Driven Design (DDD)
Domain Driven Design (DDD)Domain Driven Design (DDD)
Domain Driven Design (DDD)Tom Kocjan
 
Introduction to Amazon Elasticsearch Service
Introduction to  Amazon Elasticsearch ServiceIntroduction to  Amazon Elasticsearch Service
Introduction to Amazon Elasticsearch ServiceAmazon Web Services
 
Cadence: The Only Workflow Platform You'll Ever Need
Cadence: The Only Workflow Platform You'll Ever NeedCadence: The Only Workflow Platform You'll Ever Need
Cadence: The Only Workflow Platform You'll Ever NeedMaxim Fateev
 
Clean architecture with asp.net core
Clean architecture with asp.net coreClean architecture with asp.net core
Clean architecture with asp.net coreSam Nasr, MCSA, MVP
 
Automation - web testing with selenium
Automation - web testing with seleniumAutomation - web testing with selenium
Automation - web testing with seleniumTzirla Rozental
 
Monoliths and Microservices
Monoliths and Microservices Monoliths and Microservices
Monoliths and Microservices Bozhidar Bozhanov
 
An Introduction to JUnit 5 and how to use it with Spring boot tests and Mockito
An Introduction to JUnit 5 and how to use it with Spring boot tests and MockitoAn Introduction to JUnit 5 and how to use it with Spring boot tests and Mockito
An Introduction to JUnit 5 and how to use it with Spring boot tests and Mockitoshaunthomas999
 
Domain driven design and model driven development
Domain driven design and model driven developmentDomain driven design and model driven development
Domain driven design and model driven developmentDmitry Geyzersky
 
Design Patterns
Design PatternsDesign Patterns
Design Patternsfrgo
 
Microservices Design Patterns | Edureka
Microservices Design Patterns | EdurekaMicroservices Design Patterns | Edureka
Microservices Design Patterns | EdurekaEdureka!
 
AngularJS for Beginners
AngularJS for BeginnersAngularJS for Beginners
AngularJS for BeginnersEdureka!
 
Domain Driven Design (Ultra) Distilled
Domain Driven Design (Ultra) DistilledDomain Driven Design (Ultra) Distilled
Domain Driven Design (Ultra) DistilledNicola Costantino
 

Tendances (20)

ADF Bindings & Data Controls
ADF Bindings & Data ControlsADF Bindings & Data Controls
ADF Bindings & Data Controls
 
Hexagonal architecture with Spring Boot
Hexagonal architecture with Spring BootHexagonal architecture with Spring Boot
Hexagonal architecture with Spring Boot
 
AWS SAM으로 서버리스 아키텍쳐 운영하기 - 이재면(마이뮤직테이스트) :: AWS Community Day 2020
AWS SAM으로 서버리스 아키텍쳐 운영하기 - 이재면(마이뮤직테이스트) :: AWS Community Day 2020 AWS SAM으로 서버리스 아키텍쳐 운영하기 - 이재면(마이뮤직테이스트) :: AWS Community Day 2020
AWS SAM으로 서버리스 아키텍쳐 운영하기 - 이재면(마이뮤직테이스트) :: AWS Community Day 2020
 
Understanding Reactive Programming
Understanding Reactive ProgrammingUnderstanding Reactive Programming
Understanding Reactive Programming
 
Spring Framework - AOP
Spring Framework - AOPSpring Framework - AOP
Spring Framework - AOP
 
Spring Framework - MVC
Spring Framework - MVCSpring Framework - MVC
Spring Framework - MVC
 
Domain Driven Design (DDD)
Domain Driven Design (DDD)Domain Driven Design (DDD)
Domain Driven Design (DDD)
 
Introduction to Amazon Elasticsearch Service
Introduction to  Amazon Elasticsearch ServiceIntroduction to  Amazon Elasticsearch Service
Introduction to Amazon Elasticsearch Service
 
Cadence: The Only Workflow Platform You'll Ever Need
Cadence: The Only Workflow Platform You'll Ever NeedCadence: The Only Workflow Platform You'll Ever Need
Cadence: The Only Workflow Platform You'll Ever Need
 
Clean architecture with asp.net core
Clean architecture with asp.net coreClean architecture with asp.net core
Clean architecture with asp.net core
 
Spring boot
Spring bootSpring boot
Spring boot
 
Automation - web testing with selenium
Automation - web testing with seleniumAutomation - web testing with selenium
Automation - web testing with selenium
 
Introduction to DDD
Introduction to DDDIntroduction to DDD
Introduction to DDD
 
Monoliths and Microservices
Monoliths and Microservices Monoliths and Microservices
Monoliths and Microservices
 
An Introduction to JUnit 5 and how to use it with Spring boot tests and Mockito
An Introduction to JUnit 5 and how to use it with Spring boot tests and MockitoAn Introduction to JUnit 5 and how to use it with Spring boot tests and Mockito
An Introduction to JUnit 5 and how to use it with Spring boot tests and Mockito
 
Domain driven design and model driven development
Domain driven design and model driven developmentDomain driven design and model driven development
Domain driven design and model driven development
 
Design Patterns
Design PatternsDesign Patterns
Design Patterns
 
Microservices Design Patterns | Edureka
Microservices Design Patterns | EdurekaMicroservices Design Patterns | Edureka
Microservices Design Patterns | Edureka
 
AngularJS for Beginners
AngularJS for BeginnersAngularJS for Beginners
AngularJS for Beginners
 
Domain Driven Design (Ultra) Distilled
Domain Driven Design (Ultra) DistilledDomain Driven Design (Ultra) Distilled
Domain Driven Design (Ultra) Distilled
 

En vedette

The family
The familyThe family
The familytsiribi
 
Architecting Large Enterprise Java Projects
Architecting Large Enterprise Java ProjectsArchitecting Large Enterprise Java Projects
Architecting Large Enterprise Java ProjectsMarkus Eisele
 
Community and Java EE @ DevConf.CZ
Community and Java EE @ DevConf.CZCommunity and Java EE @ DevConf.CZ
Community and Java EE @ DevConf.CZMarkus Eisele
 
Erika Hall - Running, Yoga, + Conditioning Website Wireframe
Erika Hall - Running, Yoga, + Conditioning Website WireframeErika Hall - Running, Yoga, + Conditioning Website Wireframe
Erika Hall - Running, Yoga, + Conditioning Website WireframeErika Martin Hall
 
Using and Setting Website Sales Goal
Using and Setting Website Sales GoalUsing and Setting Website Sales Goal
Using and Setting Website Sales GoalBrandwise
 
10 Important Tips For Increasing Traffic On Your Website
10 Important Tips For Increasing Traffic On Your Website10 Important Tips For Increasing Traffic On Your Website
10 Important Tips For Increasing Traffic On Your WebsiteEminenture
 
Ebay presentation
Ebay presentationEbay presentation
Ebay presentationPickevent
 
Website analysis and Competitor Analysis and Website Wireframe
Website analysis and Competitor Analysis and Website WireframeWebsite analysis and Competitor Analysis and Website Wireframe
Website analysis and Competitor Analysis and Website WireframeSaloni Jain
 
55 New Features in Java SE 8
55 New Features in Java SE 855 New Features in Java SE 8
55 New Features in Java SE 8Simon Ritter
 
Online shopping portal: Software Project Plan
Online shopping portal: Software Project PlanOnline shopping portal: Software Project Plan
Online shopping portal: Software Project Planpiyushree nagrale
 
Powerpoint Presentation on eBay.com
Powerpoint Presentation on eBay.comPowerpoint Presentation on eBay.com
Powerpoint Presentation on eBay.commyclass08
 
Sales Interview Presentation
Sales Interview PresentationSales Interview Presentation
Sales Interview PresentationNovin
 
An interview presentation that lands senior-level jobs
An interview presentation that lands senior-level jobsAn interview presentation that lands senior-level jobs
An interview presentation that lands senior-level jobspsymar
 

En vedette (20)

The family
The familyThe family
The family
 
Architecting Large Enterprise Java Projects
Architecting Large Enterprise Java ProjectsArchitecting Large Enterprise Java Projects
Architecting Large Enterprise Java Projects
 
Community and Java EE @ DevConf.CZ
Community and Java EE @ DevConf.CZCommunity and Java EE @ DevConf.CZ
Community and Java EE @ DevConf.CZ
 
Erika Hall - Running, Yoga, + Conditioning Website Wireframe
Erika Hall - Running, Yoga, + Conditioning Website WireframeErika Hall - Running, Yoga, + Conditioning Website Wireframe
Erika Hall - Running, Yoga, + Conditioning Website Wireframe
 
Using and Setting Website Sales Goal
Using and Setting Website Sales GoalUsing and Setting Website Sales Goal
Using and Setting Website Sales Goal
 
10 Important Tips For Increasing Traffic On Your Website
10 Important Tips For Increasing Traffic On Your Website10 Important Tips For Increasing Traffic On Your Website
10 Important Tips For Increasing Traffic On Your Website
 
E-Bay
E-BayE-Bay
E-Bay
 
Ebay presentation
Ebay presentationEbay presentation
Ebay presentation
 
java swing
java swingjava swing
java swing
 
eBay inc. Case Study
eBay inc. Case Study eBay inc. Case Study
eBay inc. Case Study
 
Ebay presentation
Ebay presentationEbay presentation
Ebay presentation
 
Website analysis and Competitor Analysis and Website Wireframe
Website analysis and Competitor Analysis and Website WireframeWebsite analysis and Competitor Analysis and Website Wireframe
Website analysis and Competitor Analysis and Website Wireframe
 
Srs present
Srs presentSrs present
Srs present
 
55 New Features in Java SE 8
55 New Features in Java SE 855 New Features in Java SE 8
55 New Features in Java SE 8
 
Online shopping portal: Software Project Plan
Online shopping portal: Software Project PlanOnline shopping portal: Software Project Plan
Online shopping portal: Software Project Plan
 
Powerpoint Presentation on eBay.com
Powerpoint Presentation on eBay.comPowerpoint Presentation on eBay.com
Powerpoint Presentation on eBay.com
 
Sales Interview Presentation
Sales Interview PresentationSales Interview Presentation
Sales Interview Presentation
 
Onlineshopping
OnlineshoppingOnlineshopping
Onlineshopping
 
An interview presentation that lands senior-level jobs
An interview presentation that lands senior-level jobsAn interview presentation that lands senior-level jobs
An interview presentation that lands senior-level jobs
 
Presentation on Amazon
Presentation on AmazonPresentation on Amazon
Presentation on Amazon
 

Similaire à Java design patterns

Structural pattern 3
Structural pattern 3Structural pattern 3
Structural pattern 3Naga Muruga
 
2. Design patterns. part #2
2. Design patterns. part #22. Design patterns. part #2
2. Design patterns. part #2Leonid Maslov
 
Creational pattern 2
Creational pattern 2Creational pattern 2
Creational pattern 2Naga Muruga
 
Design patterns in Java - Monitis 2017
Design patterns in Java - Monitis 2017Design patterns in Java - Monitis 2017
Design patterns in Java - Monitis 2017Arsen Gasparyan
 
A brief overview of java frameworks
A brief overview of java frameworksA brief overview of java frameworks
A brief overview of java frameworksMD Sayem Ahmed
 
Fun Teaching MongoDB New Tricks
Fun Teaching MongoDB New TricksFun Teaching MongoDB New Tricks
Fun Teaching MongoDB New TricksMongoDB
 
Uncommon Design Patterns
Uncommon Design PatternsUncommon Design Patterns
Uncommon Design PatternsStefano Fago
 
Java concurrency model - The Future Task
Java concurrency model - The Future TaskJava concurrency model - The Future Task
Java concurrency model - The Future TaskSomenath Mukhopadhyay
 
Overview of Android Infrastructure
Overview of Android InfrastructureOverview of Android Infrastructure
Overview of Android InfrastructureAlexey Buzdin
 
Overview of Android Infrastructure
Overview of Android InfrastructureOverview of Android Infrastructure
Overview of Android InfrastructureC.T.Co
 
Use of Apache Commons and Utilities
Use of Apache Commons and UtilitiesUse of Apache Commons and Utilities
Use of Apache Commons and UtilitiesPramod Kumar
 
Workshop 23: ReactJS, React & Redux testing
Workshop 23: ReactJS, React & Redux testingWorkshop 23: ReactJS, React & Redux testing
Workshop 23: ReactJS, React & Redux testingVisual Engineering
 
P Training Presentation
P Training PresentationP Training Presentation
P Training PresentationGaurav Tyagi
 
JavaScript Growing Up
JavaScript Growing UpJavaScript Growing Up
JavaScript Growing UpDavid Padbury
 
C questions
C questionsC questions
C questionsparm112
 

Similaire à Java design patterns (20)

Design patterns
Design patternsDesign patterns
Design patterns
 
Structural pattern 3
Structural pattern 3Structural pattern 3
Structural pattern 3
 
Gephi Toolkit Tutorial
Gephi Toolkit TutorialGephi Toolkit Tutorial
Gephi Toolkit Tutorial
 
2. Design patterns. part #2
2. Design patterns. part #22. Design patterns. part #2
2. Design patterns. part #2
 
Presentation.pptx
Presentation.pptxPresentation.pptx
Presentation.pptx
 
Creational pattern 2
Creational pattern 2Creational pattern 2
Creational pattern 2
 
Design patterns in Java - Monitis 2017
Design patterns in Java - Monitis 2017Design patterns in Java - Monitis 2017
Design patterns in Java - Monitis 2017
 
A brief overview of java frameworks
A brief overview of java frameworksA brief overview of java frameworks
A brief overview of java frameworks
 
Javascript Design Patterns
Javascript Design PatternsJavascript Design Patterns
Javascript Design Patterns
 
G pars
G parsG pars
G pars
 
Fun Teaching MongoDB New Tricks
Fun Teaching MongoDB New TricksFun Teaching MongoDB New Tricks
Fun Teaching MongoDB New Tricks
 
Uncommon Design Patterns
Uncommon Design PatternsUncommon Design Patterns
Uncommon Design Patterns
 
Java concurrency model - The Future Task
Java concurrency model - The Future TaskJava concurrency model - The Future Task
Java concurrency model - The Future Task
 
Overview of Android Infrastructure
Overview of Android InfrastructureOverview of Android Infrastructure
Overview of Android Infrastructure
 
Overview of Android Infrastructure
Overview of Android InfrastructureOverview of Android Infrastructure
Overview of Android Infrastructure
 
Use of Apache Commons and Utilities
Use of Apache Commons and UtilitiesUse of Apache Commons and Utilities
Use of Apache Commons and Utilities
 
Workshop 23: ReactJS, React & Redux testing
Workshop 23: ReactJS, React & Redux testingWorkshop 23: ReactJS, React & Redux testing
Workshop 23: ReactJS, React & Redux testing
 
P Training Presentation
P Training PresentationP Training Presentation
P Training Presentation
 
JavaScript Growing Up
JavaScript Growing UpJavaScript Growing Up
JavaScript Growing Up
 
C questions
C questionsC questions
C questions
 

Dernier

%in Midrand+277-882-255-28 abortion pills for sale in midrand
%in Midrand+277-882-255-28 abortion pills for sale in midrand%in Midrand+277-882-255-28 abortion pills for sale in midrand
%in Midrand+277-882-255-28 abortion pills for sale in midrandmasabamasaba
 
%in Bahrain+277-882-255-28 abortion pills for sale in Bahrain
%in Bahrain+277-882-255-28 abortion pills for sale in Bahrain%in Bahrain+277-882-255-28 abortion pills for sale in Bahrain
%in Bahrain+277-882-255-28 abortion pills for sale in Bahrainmasabamasaba
 
AI & Machine Learning Presentation Template
AI & Machine Learning Presentation TemplateAI & Machine Learning Presentation Template
AI & Machine Learning Presentation TemplatePresentation.STUDIO
 
Exploring the Best Video Editing App.pdf
Exploring the Best Video Editing App.pdfExploring the Best Video Editing App.pdf
Exploring the Best Video Editing App.pdfproinshot.com
 
call girls in Vaishali (Ghaziabad) 🔝 >༒8448380779 🔝 genuine Escort Service 🔝✔️✔️
call girls in Vaishali (Ghaziabad) 🔝 >༒8448380779 🔝 genuine Escort Service 🔝✔️✔️call girls in Vaishali (Ghaziabad) 🔝 >༒8448380779 🔝 genuine Escort Service 🔝✔️✔️
call girls in Vaishali (Ghaziabad) 🔝 >༒8448380779 🔝 genuine Escort Service 🔝✔️✔️Delhi Call girls
 
SHRMPro HRMS Software Solutions Presentation
SHRMPro HRMS Software Solutions PresentationSHRMPro HRMS Software Solutions Presentation
SHRMPro HRMS Software Solutions PresentationShrmpro
 
VTU technical seminar 8Th Sem on Scikit-learn
VTU technical seminar 8Th Sem on Scikit-learnVTU technical seminar 8Th Sem on Scikit-learn
VTU technical seminar 8Th Sem on Scikit-learnAmarnathKambale
 
OpenChain - The Ramifications of ISO/IEC 5230 and ISO/IEC 18974 for Legal Pro...
OpenChain - The Ramifications of ISO/IEC 5230 and ISO/IEC 18974 for Legal Pro...OpenChain - The Ramifications of ISO/IEC 5230 and ISO/IEC 18974 for Legal Pro...
OpenChain - The Ramifications of ISO/IEC 5230 and ISO/IEC 18974 for Legal Pro...Shane Coughlan
 
Chinsurah Escorts ☎️8617697112 Starting From 5K to 15K High Profile Escorts ...
Chinsurah Escorts ☎️8617697112  Starting From 5K to 15K High Profile Escorts ...Chinsurah Escorts ☎️8617697112  Starting From 5K to 15K High Profile Escorts ...
Chinsurah Escorts ☎️8617697112 Starting From 5K to 15K High Profile Escorts ...Nitya salvi
 
introduction-to-automotive Andoid os-csimmonds-ndctechtown-2021.pdf
introduction-to-automotive Andoid os-csimmonds-ndctechtown-2021.pdfintroduction-to-automotive Andoid os-csimmonds-ndctechtown-2021.pdf
introduction-to-automotive Andoid os-csimmonds-ndctechtown-2021.pdfVishalKumarJha10
 
Architecture decision records - How not to get lost in the past
Architecture decision records - How not to get lost in the pastArchitecture decision records - How not to get lost in the past
Architecture decision records - How not to get lost in the pastPapp Krisztián
 
%+27788225528 love spells in new york Psychic Readings, Attraction spells,Bri...
%+27788225528 love spells in new york Psychic Readings, Attraction spells,Bri...%+27788225528 love spells in new york Psychic Readings, Attraction spells,Bri...
%+27788225528 love spells in new york Psychic Readings, Attraction spells,Bri...masabamasaba
 
call girls in Vaishali (Ghaziabad) 🔝 >༒8448380779 🔝 genuine Escort Service 🔝✔️✔️
call girls in Vaishali (Ghaziabad) 🔝 >༒8448380779 🔝 genuine Escort Service 🔝✔️✔️call girls in Vaishali (Ghaziabad) 🔝 >༒8448380779 🔝 genuine Escort Service 🔝✔️✔️
call girls in Vaishali (Ghaziabad) 🔝 >༒8448380779 🔝 genuine Escort Service 🔝✔️✔️Delhi Call girls
 
The Ultimate Test Automation Guide_ Best Practices and Tips.pdf
The Ultimate Test Automation Guide_ Best Practices and Tips.pdfThe Ultimate Test Automation Guide_ Best Practices and Tips.pdf
The Ultimate Test Automation Guide_ Best Practices and Tips.pdfkalichargn70th171
 
%+27788225528 love spells in Vancouver Psychic Readings, Attraction spells,Br...
%+27788225528 love spells in Vancouver Psychic Readings, Attraction spells,Br...%+27788225528 love spells in Vancouver Psychic Readings, Attraction spells,Br...
%+27788225528 love spells in Vancouver Psychic Readings, Attraction spells,Br...masabamasaba
 
Shapes for Sharing between Graph Data Spaces - and Epistemic Querying of RDF-...
Shapes for Sharing between Graph Data Spaces - and Epistemic Querying of RDF-...Shapes for Sharing between Graph Data Spaces - and Epistemic Querying of RDF-...
Shapes for Sharing between Graph Data Spaces - and Epistemic Querying of RDF-...Steffen Staab
 
TECUNIQUE: Success Stories: IT Service provider
TECUNIQUE: Success Stories: IT Service providerTECUNIQUE: Success Stories: IT Service provider
TECUNIQUE: Success Stories: IT Service providermohitmore19
 
W01_panagenda_Navigating-the-Future-with-The-Hitchhikers-Guide-to-Notes-and-D...
W01_panagenda_Navigating-the-Future-with-The-Hitchhikers-Guide-to-Notes-and-D...W01_panagenda_Navigating-the-Future-with-The-Hitchhikers-Guide-to-Notes-and-D...
W01_panagenda_Navigating-the-Future-with-The-Hitchhikers-Guide-to-Notes-and-D...panagenda
 
%in Stilfontein+277-882-255-28 abortion pills for sale in Stilfontein
%in Stilfontein+277-882-255-28 abortion pills for sale in Stilfontein%in Stilfontein+277-882-255-28 abortion pills for sale in Stilfontein
%in Stilfontein+277-882-255-28 abortion pills for sale in Stilfonteinmasabamasaba
 

Dernier (20)

%in Midrand+277-882-255-28 abortion pills for sale in midrand
%in Midrand+277-882-255-28 abortion pills for sale in midrand%in Midrand+277-882-255-28 abortion pills for sale in midrand
%in Midrand+277-882-255-28 abortion pills for sale in midrand
 
%in Bahrain+277-882-255-28 abortion pills for sale in Bahrain
%in Bahrain+277-882-255-28 abortion pills for sale in Bahrain%in Bahrain+277-882-255-28 abortion pills for sale in Bahrain
%in Bahrain+277-882-255-28 abortion pills for sale in Bahrain
 
AI & Machine Learning Presentation Template
AI & Machine Learning Presentation TemplateAI & Machine Learning Presentation Template
AI & Machine Learning Presentation Template
 
Exploring the Best Video Editing App.pdf
Exploring the Best Video Editing App.pdfExploring the Best Video Editing App.pdf
Exploring the Best Video Editing App.pdf
 
call girls in Vaishali (Ghaziabad) 🔝 >༒8448380779 🔝 genuine Escort Service 🔝✔️✔️
call girls in Vaishali (Ghaziabad) 🔝 >༒8448380779 🔝 genuine Escort Service 🔝✔️✔️call girls in Vaishali (Ghaziabad) 🔝 >༒8448380779 🔝 genuine Escort Service 🔝✔️✔️
call girls in Vaishali (Ghaziabad) 🔝 >༒8448380779 🔝 genuine Escort Service 🔝✔️✔️
 
SHRMPro HRMS Software Solutions Presentation
SHRMPro HRMS Software Solutions PresentationSHRMPro HRMS Software Solutions Presentation
SHRMPro HRMS Software Solutions Presentation
 
VTU technical seminar 8Th Sem on Scikit-learn
VTU technical seminar 8Th Sem on Scikit-learnVTU technical seminar 8Th Sem on Scikit-learn
VTU technical seminar 8Th Sem on Scikit-learn
 
OpenChain - The Ramifications of ISO/IEC 5230 and ISO/IEC 18974 for Legal Pro...
OpenChain - The Ramifications of ISO/IEC 5230 and ISO/IEC 18974 for Legal Pro...OpenChain - The Ramifications of ISO/IEC 5230 and ISO/IEC 18974 for Legal Pro...
OpenChain - The Ramifications of ISO/IEC 5230 and ISO/IEC 18974 for Legal Pro...
 
Chinsurah Escorts ☎️8617697112 Starting From 5K to 15K High Profile Escorts ...
Chinsurah Escorts ☎️8617697112  Starting From 5K to 15K High Profile Escorts ...Chinsurah Escorts ☎️8617697112  Starting From 5K to 15K High Profile Escorts ...
Chinsurah Escorts ☎️8617697112 Starting From 5K to 15K High Profile Escorts ...
 
introduction-to-automotive Andoid os-csimmonds-ndctechtown-2021.pdf
introduction-to-automotive Andoid os-csimmonds-ndctechtown-2021.pdfintroduction-to-automotive Andoid os-csimmonds-ndctechtown-2021.pdf
introduction-to-automotive Andoid os-csimmonds-ndctechtown-2021.pdf
 
Architecture decision records - How not to get lost in the past
Architecture decision records - How not to get lost in the pastArchitecture decision records - How not to get lost in the past
Architecture decision records - How not to get lost in the past
 
%+27788225528 love spells in new york Psychic Readings, Attraction spells,Bri...
%+27788225528 love spells in new york Psychic Readings, Attraction spells,Bri...%+27788225528 love spells in new york Psychic Readings, Attraction spells,Bri...
%+27788225528 love spells in new york Psychic Readings, Attraction spells,Bri...
 
call girls in Vaishali (Ghaziabad) 🔝 >༒8448380779 🔝 genuine Escort Service 🔝✔️✔️
call girls in Vaishali (Ghaziabad) 🔝 >༒8448380779 🔝 genuine Escort Service 🔝✔️✔️call girls in Vaishali (Ghaziabad) 🔝 >༒8448380779 🔝 genuine Escort Service 🔝✔️✔️
call girls in Vaishali (Ghaziabad) 🔝 >༒8448380779 🔝 genuine Escort Service 🔝✔️✔️
 
The Ultimate Test Automation Guide_ Best Practices and Tips.pdf
The Ultimate Test Automation Guide_ Best Practices and Tips.pdfThe Ultimate Test Automation Guide_ Best Practices and Tips.pdf
The Ultimate Test Automation Guide_ Best Practices and Tips.pdf
 
%+27788225528 love spells in Vancouver Psychic Readings, Attraction spells,Br...
%+27788225528 love spells in Vancouver Psychic Readings, Attraction spells,Br...%+27788225528 love spells in Vancouver Psychic Readings, Attraction spells,Br...
%+27788225528 love spells in Vancouver Psychic Readings, Attraction spells,Br...
 
Shapes for Sharing between Graph Data Spaces - and Epistemic Querying of RDF-...
Shapes for Sharing between Graph Data Spaces - and Epistemic Querying of RDF-...Shapes for Sharing between Graph Data Spaces - and Epistemic Querying of RDF-...
Shapes for Sharing between Graph Data Spaces - and Epistemic Querying of RDF-...
 
TECUNIQUE: Success Stories: IT Service provider
TECUNIQUE: Success Stories: IT Service providerTECUNIQUE: Success Stories: IT Service provider
TECUNIQUE: Success Stories: IT Service provider
 
Microsoft AI Transformation Partner Playbook.pdf
Microsoft AI Transformation Partner Playbook.pdfMicrosoft AI Transformation Partner Playbook.pdf
Microsoft AI Transformation Partner Playbook.pdf
 
W01_panagenda_Navigating-the-Future-with-The-Hitchhikers-Guide-to-Notes-and-D...
W01_panagenda_Navigating-the-Future-with-The-Hitchhikers-Guide-to-Notes-and-D...W01_panagenda_Navigating-the-Future-with-The-Hitchhikers-Guide-to-Notes-and-D...
W01_panagenda_Navigating-the-Future-with-The-Hitchhikers-Guide-to-Notes-and-D...
 
%in Stilfontein+277-882-255-28 abortion pills for sale in Stilfontein
%in Stilfontein+277-882-255-28 abortion pills for sale in Stilfontein%in Stilfontein+277-882-255-28 abortion pills for sale in Stilfontein
%in Stilfontein+277-882-255-28 abortion pills for sale in Stilfontein
 

Java design patterns

  • 2. What Are Design Patterns? A solution to a language independent OO Problem. If the solution is a reoccurring over time, it becomes a “Pattern”. .net Java C++ C# VB.net
  • 3. Factory Pattern Definition The Factory pattern provides a way to use an instance as a object factory. The factory can return an instance of one of several possible classes (in a subclass hierarchy), depending on the data provided to it. Where to use 1) When a class can't anticipate which kind of class of object it must create. 2) You want to localize the knowledge of which class gets created. 3) When you have classes that is derived from the same subclasses, or they may in fact be unrelated classes that just share the same interface. Either way, the methods in these class instances are the same and can be used interchangeably. 4) When you want to insulate the client from the actual type that is being instantiated.
  • 5. Factory Patternpublic abstract class Product { public void writeName(String name) { System.out.println("My name is "+name); } } public class ProductA extends Product { } public class ProductB extends Product { public void writeName(String name) { StringBuilder tempName = new StringBuilder().append(name); System.out.println("My reversed name is" + tempName.reverse()); } } public class ProductFactory { public Product createProduct(String type) { if(type.equals("B")) return new ProductB(); else return new ProductA(); } } ProductFactory pf = new ProductFactory(); Product prod; prod = pf.createProduct("A"); prod.writeName("John Doe"); prod = pf.createProduct("B"); prod.writeName("John Doe"); Connection, Statement, ResultSet
  • 6. Proxy Pattern DefinitionDefinition A Proxy is a structural pattern that provides a stand-in for another object in order to control access to it. Where to useWhere to use 1) When the creation of one object is relatively expensive it can be a good idea to replace it with a proxy that can make sure that instantiation of the expensive object is kept to a minimum. 2) Proxy pattern implementation allows for login and authority checking before one reaches the actual object that's requested. 3) Can provide a local representation for an object in a remote location.
  • 8. Proxy Patterninterface IExploded { public void pumpPetrol(String arg); } class ProxyExploded implements IExploded{ public void pumpPetrol(String arg){ System.out.println("Pumping. "); } } public class Pattern_Proxy implements IExploded { StringBuffer strbuf = new StringBuffer(); public void pumpPetrol(String arg){ strbuf.append(arg); System.out.println("Pumping. "); if(strbuf.length() >70){ explosion2(); strbuf.delete(0, strbuf.length()); System.exit(0); }else if(strbuf.length()>50){ explosion1(); } } public void explosion1(){ System.out.println("System is about to Explode"); } public void explosion2(){ System.out.println("System has exploded... Kaboom!!.. rn”+ ”To Much Petrol.."+strbuf.length()+" L"); } } public static void main(String arg[]) { IExploded prox = new Pattern_Proxy(); for(int y=0; y<50; y++){ prox.pumpPetrol("Petrol."); } }
  • 9. Singleton Pattern Definition The Singleton pattern provides the possibility to control the number of instances (mostly one) that are allowed to be made. We also receive a global point of access to it (them). Where to use When only one instance or a specific number of instances of a class are allowed. Facade objects are often Singletons because only one Facade object is required. Benefits •Controlled access to unique instance. •Reduced name space. •Allows refinement of operations and representations.
  • 11. Singleton Pattern public class MapLogger { private static MapLogger mapper=null; // Prevent clients from using the constructor private MapLogger() { /* Nothing Here :-) */ } //Control the accessible (allowed) instances public static MapLogger getMapLogger() { if (mapper == null) { mapper = new MapLogger(); } return mapper; } public synchronized void put(String key, String val) { // Write to Map/Hashtable... } }
  • 12. Flyweight Pattern Definition The Flyweight pattern provides a mechanism by which you can avoid creating a large number of 'expensive' objects and instead reuse existing instances to represent new ones. Where to use 1) When there is a very large number of objects that may not fit in memory. 2) When most of an objects state can be stored on disk or calculated at Runtime. 3) When there are groups of objects that share state. 4) When the remaining state can be factored into a much smaller number of objects with shared state. Benefits Reduce the number of objects created, decrease memory footprint and increase performance.
  • 14. Flyweight Patternclass Godzilla { private int row; public Godzilla( int theRow ) { row = theRow; System.out.println( "ctor: " + row ); } void report( int theCol ) { System.out.print( " " + row + theCol ); } } class Factory { private Godzilla[] pool; public Factory( int maxRows ) { pool = new Godzilla[maxRows]; } public Godzilla getFlyweight( int theRow ) { if (pool[theRow] == null) pool[theRow] = new Godzilla( theRow ); return pool[theRow]; } } public class FlyweightDemo { public static final int ROWS = 6, COLS = 10; public static void main( String[] args ) { Factory theFactory = new Factory( ROWS ); for (int i=0; i < ROWS; i++) { for (int j=0; j < COLS; j++) theFactory.getFlyweight( i ).report( j ); System.out.println(); } } }
  • 15. Observer Pattern Definition Proxy pattern is a behavioral pattern. It defines a one-to-many dependency between objects, so that when one object changes its state, all its dependent objects are notified and updated. Where to use 1) When state changes of a one object must be reflected in other objects without depending on the state changing process of the object (reduce the coupling between the objects).
  • 17. Observer Pattern public class WeatherStation extends Observable implements Runnable { public void run() { String report = this.getCurrentReport(); notifyObservers( report ); } } public class WeatherObserver implements Observer { private String response; public void update (Observable obj, Object arg) { response = (String)arg; } }
  • 18. Observer Pattern public class WeatherClient { public static void main(String args[]) { // create a WheatherStation instance final WeatherStation station = new WeatherStation(); // create an observer final WeatherObserver weatherObserver = new WeatherObserver(); // subscribe the observer to the event source station.addObserver( weatherObserver ); // starts the event thread Thread thread = new Thread(station); thread.start(); } }
  • 19. Decorator Pattern Definition Decorator pattern is a structural pattern. Intent of the pattern is to add additional responsibilities dynamically to an object. Where to use 1) When you want the responsibilities added to or removed from an object at runtime. 2) When using inheritance results in a large number of subclasses.
  • 21. Decorator Pattern // The Coffee Interface defines the functionality of Coffee implemented by decorator public interface Coffee { // returns the cost of the coffee public double getCost(); // returns the ingredients of the coffee public String getIngredients(); } // implementation of a simple coffee without any extra ingredients public class SimpleCoffee implements Coffee { public double getCost() { return 1; } public String getIngredients() { return "Coffee"; } }
  • 22. Decorator Pattern // abstract decorator class - note that it implements Coffee interface abstract public class CoffeeDecorator implements Coffee { protected final Coffee decoratedCoffee; protected String ingredientSeparator = ", "; public CoffeeDecorator(Coffee decoratedCoffee) { this.decoratedCoffee = decoratedCoffee; } public double getCost() { // implementing methods of the interface return decoratedCoffee.getCost(); } public String getIngredients() { return decoratedCoffee.getIngredients(); } }
  • 23. Decorator Pattern // Decorator Milk that mixes milk with coffee // note it extends CoffeeDecorator public class Milk extends CoffeeDecorator { public Milk(Coffee decoratedCoffee) { super(decoratedCoffee); } public double getCost() { // overriding methods defined in the abstract superclass return super.getCost() + 0.5; } public String getIngredients() { return super.getIngredients() + ingredientSeparator + "Milk"; } }
  • 24. Decorator Pattern public class Whip extends CoffeeDecorator { public Whip(Coffee decoratedCoffee) { super(decoratedCoffee); } public double getCost() { return super.getCost() + 0.7; } public String getIngredients() { return super.getIngredients() + ingredientSeparator + "Whip"; } }
  • 25. Decorator Pattern public class CoffeMaker { public static void main(String[] args) { Coffee c = new SimpleCoffee(); System.out.println("Cost: " + c.getCost() + "; Ingredients: " + c.getIngredients()); c = new Milk(c); System.out.println("Cost: " + c.getCost() + "; Ingredients: " + c.getIngredients()); } }
  • 26. Decorator Pattern public class Whip extends CoffeeDecorator { public Whip(Coffee decoratedCoffee) { super(decoratedCoffee); } public double getCost() { return super.getCost() + 0.7; } public String getIngredients() { return super.getIngredients() + ingredientSeparator + "Whip"; } }