SlideShare une entreprise Scribd logo
1  sur  32
2
3
 Name: Factory Method
 Intent: Define an interface for creating an object, but
let subclasses decide which class to instantiate. Defer
instantiation to subclasses.
 Problem: A class needs to instantiate a derivation of
another class, but doesn't know which one. Factory
Method allows a derived class to make this decision.
 Solution: Provides an abstraction or an interface and
lets subclass or implementing classes decide which
class or method should be instantiated or called, based
on the conditions or parameters given.
4
Product is the interface for the type of object that the Factory Method
creates. Creator is the interface that defines the Factory Method.
5
 You want to connect to a database but you want to
decide at run time which type of database it is (i.e.
SQL, Oracle, MySQL etc.)
 Apply Factory Method
6
7
public interface ConnectionFactory{
public Connection createConnection();
}
class MyConnectionFactory implements ConnectionFactory{
public String type;
public MyConnectionFactory(String t){
type = t; }
public Connection createConnection(){
if(type.equals("Oracle")){
return new OracleConnection(); }
else if(type.equals("SQL")){
return new SQLConnection(); }
else{ return new MySQLConnection(); }
}
}
8
public interface Connection{
public String description();
public void open();
public void close();
}
class SQLConnection implements Connection{
public String description(){ return "SQL";} }
class MySQLConnection implements Connection{
public String description(){ return "MySQL” ;} }
class OracleConnection implements Connection{
public String description(){ return "Oracle"; } }
These three implementing classes should have definition for Open &
Close Methods of above interface as well to be concrete.
9
class TestConnectionFactory{
public static void main(String[]args){
MyConnectionFactory con = new
MyConnectionFactory("My SQL");
Connection con2 = con.createConnection();
System.out.println("Connection Created: ");
System.out.println(con2.description());
}
}
10
11
 Name: Strategy
 Intent: Define a family of algorithms, encapsulate each
one, and make them interchangeable. Strategy lets the
algorithm vary independently from clients that use it.
 Problem: How to design for varying, but related,
algorithms or policies?
 Solution: Define each algorithm/policy/strategy in a
separate class, with a common interface.
12
13
 Strategy : declares an interface common to all
supported algorithms. Context uses this interface to
call the algorithm defined by a ConcreteStrategy.
 ConcreteStrategy: implements the algorithm using
the Strategy interface.
 Context : is configured with a ConcreteStrategy
object.
 maintains a reference to a Strategy object.
 may define an interface that lets Strategy access its data.
14
 We are developing an e-commerce application where
we need to calculate Tax…there are two tax
strategies…Tax rate is 10% for old citizens and 15%
otherwise.
15
16
public interface TaxStrategy{
public void calcTax();
}
class Citizen implements TaxStrategy{
public void calcTax(){
System.out.println("Tax Deduction @ 15%");}}
class OldCitizen implements TaxStrategy{
public void calcTax(){
System.out.println("Tax Deduction @ 10%");}}
17
class TaxContext{
private TaxStrategy TS;
public void setStrategy(TaxStrategy ts){ TS=ts; }
public void calculateTax(){ TS.calcTax(); }}
class Client{
public static void main(String[]args){
TaxContext cont = new TaxContext();
cont.setStrategy(new Citizen());
cont.calculateTax();
}
}
18
 There are different Taxing algorithms or strategies, and
they change over time. Who should create the
strategy?
 A straightforward approach is to apply the Factory
pattern
19
20
21
public interface StrategyFactory{
public TaxStrategy getStrategy();
}
class MyStrategy implements StrategyFactory{
String type;
public MyStrategy(String t){ type=t; }
public TaxStrategy getStrategy(){
if(type.equals("Citizen"))
return new Citizen();
else
return new OldCitizen();} }
22
class Client{
public static void main(String[]args){
MyStrategy m = new MyStrategy("Citizen");
TaxContext cont = new TaxContext();
cont.setStrategy(m.getStrategy());
cont.calculateTax();
}
}
23
24
 Name: Proxy
 Intent: Provide a surrogate or placeholder for another
object to control access to it.
 Problem: You want to control the access to an object
for different reasons. You may want to delay the
creation / initialization of expensive objects or you
may want to provide a local representation of a remote
object.
 Solution: Provide a Stub / placeholder for actual
object.
25
26
 Subject - Interface implemented by the RealSubject
and representing its services. The interface must be
implemented by the proxy as well so that the proxy can
be used in any location where the RealSubject can be
used.
 Proxy- Maintains a reference that allows the Proxy to
access the RealSubject. Implements the same interface
implemented by the RealSubject so that the Proxy can
be substituted for the RealSubject. Controls access to
the RealSubject and may be responsible for its creation
and deletion.
 RealSubject- the real object that the proxy represents.
27
 Consider an image viewer program that lists and
displays high resolution photos. The program has to
show a list of all photos however it does not need to
display the actual photo until the user selects an image
item from a list.
28
29
public interface Image{
public void showImage();
}
class HRImage implements Image{
public HRImage(){
System.out.println("loading a High Resolution image");
}
public void showImage(){
System.out.println("Showing a High Resolution Image");
}
}
30
class ProxyImage implements Image{
private Image proxyImage;
public ProxyImage(){
System.out.println("Loading a proxy image");}
public void showImage(){
proxyImage = (HRImage)new HRImage();
proxyImage.showImage();} }
class ImageViewer{
public static void main(String[]args){
Image HRImage1 = new ProxyImage();
Image HRImage2 = new ProxyImage();
Image HRImage3 = new ProxyImage();
HRImage1.showImage();} }
31
 Virtual Proxies: delaying the creation and
initialization of expensive objects until needed, where
the objects are created on demand
 Remote Proxies: providing a local representation for
an object that is in a different address space. A
common example is Java RMI stub objects. The stub
object acts as a proxy where invoking methods on the
stub would cause the stub to communicate and invoke
methods on a remote object (called skeleton) found on
a different machine.
 Protection Proxies: where a proxy controls access to
RealSubject methods, by giving access to some objects
while denying access to others.
32

Contenu connexe

Similaire à Factory method & strategy pattern

Proxy & adapter pattern
Proxy & adapter patternProxy & adapter pattern
Proxy & adapter patternbabak danyal
 
Structural pattern 3
Structural pattern 3Structural pattern 3
Structural pattern 3Naga Muruga
 
Desing pattern prototype-Factory Method, Prototype and Builder
Desing pattern prototype-Factory Method, Prototype and Builder Desing pattern prototype-Factory Method, Prototype and Builder
Desing pattern prototype-Factory Method, Prototype and Builder paramisoft
 
CIS407AWk2iLabDefault.aspx Greetings and Salutations.docx
CIS407AWk2iLabDefault.aspx        Greetings and Salutations.docxCIS407AWk2iLabDefault.aspx        Greetings and Salutations.docx
CIS407AWk2iLabDefault.aspx Greetings and Salutations.docxclarebernice
 
softshake 2014 - Java EE
softshake 2014 - Java EEsoftshake 2014 - Java EE
softshake 2014 - Java EEAlexis Hassler
 
Repository Pattern in MVC3 Application with Entity Framework
Repository Pattern in MVC3 Application with Entity FrameworkRepository Pattern in MVC3 Application with Entity Framework
Repository Pattern in MVC3 Application with Entity FrameworkAkhil Mittal
 
Proxy Deep Dive JUG Saxony Day 2015-10-02
Proxy Deep Dive JUG Saxony Day 2015-10-02Proxy Deep Dive JUG Saxony Day 2015-10-02
Proxy Deep Dive JUG Saxony Day 2015-10-02Sven Ruppert
 
.NET Portfolio
.NET Portfolio.NET Portfolio
.NET Portfoliomwillmer
 
Java design patterns
Java design patternsJava design patterns
Java design patternsShawn Brito
 
MCS,BCS-7(A,B) Visual programming Syllabus for Final exams @ ISP
MCS,BCS-7(A,B) Visual programming Syllabus for Final exams @ ISPMCS,BCS-7(A,B) Visual programming Syllabus for Final exams @ ISP
MCS,BCS-7(A,B) Visual programming Syllabus for Final exams @ ISPAli Shah
 
Creational pattern 2
Creational pattern 2Creational pattern 2
Creational pattern 2Naga Muruga
 
React Hooks Best Practices in 2022.pptx
React Hooks Best Practices in 2022.pptxReact Hooks Best Practices in 2022.pptx
React Hooks Best Practices in 2022.pptxBOSC Tech Labs
 
lecture10-patterns.ppt
lecture10-patterns.pptlecture10-patterns.ppt
lecture10-patterns.pptAnkitPangasa1
 
lecture10-patterns.ppt
lecture10-patterns.pptlecture10-patterns.ppt
lecture10-patterns.pptbryafaissal
 
ChircuVictor StefircaMadalin rad_aspmvc3_wcf_vs2010
ChircuVictor StefircaMadalin rad_aspmvc3_wcf_vs2010ChircuVictor StefircaMadalin rad_aspmvc3_wcf_vs2010
ChircuVictor StefircaMadalin rad_aspmvc3_wcf_vs2010vchircu
 
09 Application Design
09 Application Design09 Application Design
09 Application DesignRanjan Kumar
 

Similaire à Factory method & strategy pattern (20)

Proxy & adapter pattern
Proxy & adapter patternProxy & adapter pattern
Proxy & adapter pattern
 
Structural pattern 3
Structural pattern 3Structural pattern 3
Structural pattern 3
 
Working with Servlets
Working with ServletsWorking with Servlets
Working with Servlets
 
Desing pattern prototype-Factory Method, Prototype and Builder
Desing pattern prototype-Factory Method, Prototype and Builder Desing pattern prototype-Factory Method, Prototype and Builder
Desing pattern prototype-Factory Method, Prototype and Builder
 
Mvc acchitecture
Mvc acchitectureMvc acchitecture
Mvc acchitecture
 
CIS407AWk2iLabDefault.aspx Greetings and Salutations.docx
CIS407AWk2iLabDefault.aspx        Greetings and Salutations.docxCIS407AWk2iLabDefault.aspx        Greetings and Salutations.docx
CIS407AWk2iLabDefault.aspx Greetings and Salutations.docx
 
softshake 2014 - Java EE
softshake 2014 - Java EEsoftshake 2014 - Java EE
softshake 2014 - Java EE
 
Eclipse Tricks
Eclipse TricksEclipse Tricks
Eclipse Tricks
 
Repository Pattern in MVC3 Application with Entity Framework
Repository Pattern in MVC3 Application with Entity FrameworkRepository Pattern in MVC3 Application with Entity Framework
Repository Pattern in MVC3 Application with Entity Framework
 
Proxy Deep Dive JUG Saxony Day 2015-10-02
Proxy Deep Dive JUG Saxony Day 2015-10-02Proxy Deep Dive JUG Saxony Day 2015-10-02
Proxy Deep Dive JUG Saxony Day 2015-10-02
 
.NET Portfolio
.NET Portfolio.NET Portfolio
.NET Portfolio
 
Java design patterns
Java design patternsJava design patterns
Java design patterns
 
MCS,BCS-7(A,B) Visual programming Syllabus for Final exams @ ISP
MCS,BCS-7(A,B) Visual programming Syllabus for Final exams @ ISPMCS,BCS-7(A,B) Visual programming Syllabus for Final exams @ ISP
MCS,BCS-7(A,B) Visual programming Syllabus for Final exams @ ISP
 
Creational pattern 2
Creational pattern 2Creational pattern 2
Creational pattern 2
 
React Hooks Best Practices in 2022.pptx
React Hooks Best Practices in 2022.pptxReact Hooks Best Practices in 2022.pptx
React Hooks Best Practices in 2022.pptx
 
lecture10-patterns.ppt
lecture10-patterns.pptlecture10-patterns.ppt
lecture10-patterns.ppt
 
lecture10-patterns.ppt
lecture10-patterns.pptlecture10-patterns.ppt
lecture10-patterns.ppt
 
Design Patterns
Design PatternsDesign Patterns
Design Patterns
 
ChircuVictor StefircaMadalin rad_aspmvc3_wcf_vs2010
ChircuVictor StefircaMadalin rad_aspmvc3_wcf_vs2010ChircuVictor StefircaMadalin rad_aspmvc3_wcf_vs2010
ChircuVictor StefircaMadalin rad_aspmvc3_wcf_vs2010
 
09 Application Design
09 Application Design09 Application Design
09 Application Design
 

Plus de babak danyal

Easy Steps to implement UDP Server and Client Sockets
Easy Steps to implement UDP Server and Client SocketsEasy Steps to implement UDP Server and Client Sockets
Easy Steps to implement UDP Server and Client Socketsbabak danyal
 
Java IO Package and Streams
Java IO Package and StreamsJava IO Package and Streams
Java IO Package and Streamsbabak danyal
 
Swing and Graphical User Interface in Java
Swing and Graphical User Interface in JavaSwing and Graphical User Interface in Java
Swing and Graphical User Interface in Javababak danyal
 
block ciphers and the des
block ciphers and the desblock ciphers and the des
block ciphers and the desbabak danyal
 
key distribution in network security
key distribution in network securitykey distribution in network security
key distribution in network securitybabak danyal
 
Lecture10 Signal and Systems
Lecture10 Signal and SystemsLecture10 Signal and Systems
Lecture10 Signal and Systemsbabak danyal
 
Lecture8 Signal and Systems
Lecture8 Signal and SystemsLecture8 Signal and Systems
Lecture8 Signal and Systemsbabak danyal
 
Lecture7 Signal and Systems
Lecture7 Signal and SystemsLecture7 Signal and Systems
Lecture7 Signal and Systemsbabak danyal
 
Lecture6 Signal and Systems
Lecture6 Signal and SystemsLecture6 Signal and Systems
Lecture6 Signal and Systemsbabak danyal
 
Lecture5 Signal and Systems
Lecture5 Signal and SystemsLecture5 Signal and Systems
Lecture5 Signal and Systemsbabak danyal
 
Lecture4 Signal and Systems
Lecture4  Signal and SystemsLecture4  Signal and Systems
Lecture4 Signal and Systemsbabak danyal
 
Lecture3 Signal and Systems
Lecture3 Signal and SystemsLecture3 Signal and Systems
Lecture3 Signal and Systemsbabak danyal
 
Lecture2 Signal and Systems
Lecture2 Signal and SystemsLecture2 Signal and Systems
Lecture2 Signal and Systemsbabak danyal
 
Lecture1 Intro To Signa
Lecture1 Intro To SignaLecture1 Intro To Signa
Lecture1 Intro To Signababak danyal
 
Lecture9 Signal and Systems
Lecture9 Signal and SystemsLecture9 Signal and Systems
Lecture9 Signal and Systemsbabak danyal
 
Cns 13f-lec03- Classical Encryption Techniques
Cns 13f-lec03- Classical Encryption TechniquesCns 13f-lec03- Classical Encryption Techniques
Cns 13f-lec03- Classical Encryption Techniquesbabak danyal
 
Classical Encryption Techniques in Network Security
Classical Encryption Techniques in Network SecurityClassical Encryption Techniques in Network Security
Classical Encryption Techniques in Network Securitybabak danyal
 

Plus de babak danyal (20)

applist
applistapplist
applist
 
Easy Steps to implement UDP Server and Client Sockets
Easy Steps to implement UDP Server and Client SocketsEasy Steps to implement UDP Server and Client Sockets
Easy Steps to implement UDP Server and Client Sockets
 
Java IO Package and Streams
Java IO Package and StreamsJava IO Package and Streams
Java IO Package and Streams
 
Swing and Graphical User Interface in Java
Swing and Graphical User Interface in JavaSwing and Graphical User Interface in Java
Swing and Graphical User Interface in Java
 
Tcp sockets
Tcp socketsTcp sockets
Tcp sockets
 
block ciphers and the des
block ciphers and the desblock ciphers and the des
block ciphers and the des
 
key distribution in network security
key distribution in network securitykey distribution in network security
key distribution in network security
 
Lecture10 Signal and Systems
Lecture10 Signal and SystemsLecture10 Signal and Systems
Lecture10 Signal and Systems
 
Lecture8 Signal and Systems
Lecture8 Signal and SystemsLecture8 Signal and Systems
Lecture8 Signal and Systems
 
Lecture7 Signal and Systems
Lecture7 Signal and SystemsLecture7 Signal and Systems
Lecture7 Signal and Systems
 
Lecture6 Signal and Systems
Lecture6 Signal and SystemsLecture6 Signal and Systems
Lecture6 Signal and Systems
 
Lecture5 Signal and Systems
Lecture5 Signal and SystemsLecture5 Signal and Systems
Lecture5 Signal and Systems
 
Lecture4 Signal and Systems
Lecture4  Signal and SystemsLecture4  Signal and Systems
Lecture4 Signal and Systems
 
Lecture3 Signal and Systems
Lecture3 Signal and SystemsLecture3 Signal and Systems
Lecture3 Signal and Systems
 
Lecture2 Signal and Systems
Lecture2 Signal and SystemsLecture2 Signal and Systems
Lecture2 Signal and Systems
 
Lecture1 Intro To Signa
Lecture1 Intro To SignaLecture1 Intro To Signa
Lecture1 Intro To Signa
 
Lecture9 Signal and Systems
Lecture9 Signal and SystemsLecture9 Signal and Systems
Lecture9 Signal and Systems
 
Lecture9
Lecture9Lecture9
Lecture9
 
Cns 13f-lec03- Classical Encryption Techniques
Cns 13f-lec03- Classical Encryption TechniquesCns 13f-lec03- Classical Encryption Techniques
Cns 13f-lec03- Classical Encryption Techniques
 
Classical Encryption Techniques in Network Security
Classical Encryption Techniques in Network SecurityClassical Encryption Techniques in Network Security
Classical Encryption Techniques in Network Security
 

Dernier

This PowerPoint helps students to consider the concept of infinity.
This PowerPoint helps students to consider the concept of infinity.This PowerPoint helps students to consider the concept of infinity.
This PowerPoint helps students to consider the concept of infinity.christianmathematics
 
1029 - Danh muc Sach Giao Khoa 10 . pdf
1029 -  Danh muc Sach Giao Khoa 10 . pdf1029 -  Danh muc Sach Giao Khoa 10 . pdf
1029 - Danh muc Sach Giao Khoa 10 . pdfQucHHunhnh
 
Dyslexia AI Workshop for Slideshare.pptx
Dyslexia AI Workshop for Slideshare.pptxDyslexia AI Workshop for Slideshare.pptx
Dyslexia AI Workshop for Slideshare.pptxcallscotland1987
 
ICT role in 21st century education and it's challenges.
ICT role in 21st century education and it's challenges.ICT role in 21st century education and it's challenges.
ICT role in 21st century education and it's challenges.MaryamAhmad92
 
Fostering Friendships - Enhancing Social Bonds in the Classroom
Fostering Friendships - Enhancing Social Bonds  in the ClassroomFostering Friendships - Enhancing Social Bonds  in the Classroom
Fostering Friendships - Enhancing Social Bonds in the ClassroomPooky Knightsmith
 
SKILL OF INTRODUCING THE LESSON MICRO SKILLS.pptx
SKILL OF INTRODUCING THE LESSON MICRO SKILLS.pptxSKILL OF INTRODUCING THE LESSON MICRO SKILLS.pptx
SKILL OF INTRODUCING THE LESSON MICRO SKILLS.pptxAmanpreet Kaur
 
Food safety_Challenges food safety laboratories_.pdf
Food safety_Challenges food safety laboratories_.pdfFood safety_Challenges food safety laboratories_.pdf
Food safety_Challenges food safety laboratories_.pdfSherif Taha
 
ICT Role in 21st Century Education & its Challenges.pptx
ICT Role in 21st Century Education & its Challenges.pptxICT Role in 21st Century Education & its Challenges.pptx
ICT Role in 21st Century Education & its Challenges.pptxAreebaZafar22
 
Holdier Curriculum Vitae (April 2024).pdf
Holdier Curriculum Vitae (April 2024).pdfHoldier Curriculum Vitae (April 2024).pdf
Holdier Curriculum Vitae (April 2024).pdfagholdier
 
General Principles of Intellectual Property: Concepts of Intellectual Proper...
General Principles of Intellectual Property: Concepts of Intellectual  Proper...General Principles of Intellectual Property: Concepts of Intellectual  Proper...
General Principles of Intellectual Property: Concepts of Intellectual Proper...Poonam Aher Patil
 
How to Give a Domain for a Field in Odoo 17
How to Give a Domain for a Field in Odoo 17How to Give a Domain for a Field in Odoo 17
How to Give a Domain for a Field in Odoo 17Celine George
 
Explore beautiful and ugly buildings. Mathematics helps us create beautiful d...
Explore beautiful and ugly buildings. Mathematics helps us create beautiful d...Explore beautiful and ugly buildings. Mathematics helps us create beautiful d...
Explore beautiful and ugly buildings. Mathematics helps us create beautiful d...christianmathematics
 
1029-Danh muc Sach Giao Khoa khoi 6.pdf
1029-Danh muc Sach Giao Khoa khoi  6.pdf1029-Danh muc Sach Giao Khoa khoi  6.pdf
1029-Danh muc Sach Giao Khoa khoi 6.pdfQucHHunhnh
 
Sociology 101 Demonstration of Learning Exhibit
Sociology 101 Demonstration of Learning ExhibitSociology 101 Demonstration of Learning Exhibit
Sociology 101 Demonstration of Learning Exhibitjbellavia9
 
How to Manage Global Discount in Odoo 17 POS
How to Manage Global Discount in Odoo 17 POSHow to Manage Global Discount in Odoo 17 POS
How to Manage Global Discount in Odoo 17 POSCeline George
 
TỔNG ÔN TẬP THI VÀO LỚP 10 MÔN TIẾNG ANH NĂM HỌC 2023 - 2024 CÓ ĐÁP ÁN (NGỮ Â...
TỔNG ÔN TẬP THI VÀO LỚP 10 MÔN TIẾNG ANH NĂM HỌC 2023 - 2024 CÓ ĐÁP ÁN (NGỮ Â...TỔNG ÔN TẬP THI VÀO LỚP 10 MÔN TIẾNG ANH NĂM HỌC 2023 - 2024 CÓ ĐÁP ÁN (NGỮ Â...
TỔNG ÔN TẬP THI VÀO LỚP 10 MÔN TIẾNG ANH NĂM HỌC 2023 - 2024 CÓ ĐÁP ÁN (NGỮ Â...Nguyen Thanh Tu Collection
 
Micro-Scholarship, What it is, How can it help me.pdf
Micro-Scholarship, What it is, How can it help me.pdfMicro-Scholarship, What it is, How can it help me.pdf
Micro-Scholarship, What it is, How can it help me.pdfPoh-Sun Goh
 
Activity 01 - Artificial Culture (1).pdf
Activity 01 - Artificial Culture (1).pdfActivity 01 - Artificial Culture (1).pdf
Activity 01 - Artificial Culture (1).pdfciinovamais
 
The basics of sentences session 3pptx.pptx
The basics of sentences session 3pptx.pptxThe basics of sentences session 3pptx.pptx
The basics of sentences session 3pptx.pptxheathfieldcps1
 
Basic Civil Engineering first year Notes- Chapter 4 Building.pptx
Basic Civil Engineering first year Notes- Chapter 4 Building.pptxBasic Civil Engineering first year Notes- Chapter 4 Building.pptx
Basic Civil Engineering first year Notes- Chapter 4 Building.pptxDenish Jangid
 

Dernier (20)

This PowerPoint helps students to consider the concept of infinity.
This PowerPoint helps students to consider the concept of infinity.This PowerPoint helps students to consider the concept of infinity.
This PowerPoint helps students to consider the concept of infinity.
 
1029 - Danh muc Sach Giao Khoa 10 . pdf
1029 -  Danh muc Sach Giao Khoa 10 . pdf1029 -  Danh muc Sach Giao Khoa 10 . pdf
1029 - Danh muc Sach Giao Khoa 10 . pdf
 
Dyslexia AI Workshop for Slideshare.pptx
Dyslexia AI Workshop for Slideshare.pptxDyslexia AI Workshop for Slideshare.pptx
Dyslexia AI Workshop for Slideshare.pptx
 
ICT role in 21st century education and it's challenges.
ICT role in 21st century education and it's challenges.ICT role in 21st century education and it's challenges.
ICT role in 21st century education and it's challenges.
 
Fostering Friendships - Enhancing Social Bonds in the Classroom
Fostering Friendships - Enhancing Social Bonds  in the ClassroomFostering Friendships - Enhancing Social Bonds  in the Classroom
Fostering Friendships - Enhancing Social Bonds in the Classroom
 
SKILL OF INTRODUCING THE LESSON MICRO SKILLS.pptx
SKILL OF INTRODUCING THE LESSON MICRO SKILLS.pptxSKILL OF INTRODUCING THE LESSON MICRO SKILLS.pptx
SKILL OF INTRODUCING THE LESSON MICRO SKILLS.pptx
 
Food safety_Challenges food safety laboratories_.pdf
Food safety_Challenges food safety laboratories_.pdfFood safety_Challenges food safety laboratories_.pdf
Food safety_Challenges food safety laboratories_.pdf
 
ICT Role in 21st Century Education & its Challenges.pptx
ICT Role in 21st Century Education & its Challenges.pptxICT Role in 21st Century Education & its Challenges.pptx
ICT Role in 21st Century Education & its Challenges.pptx
 
Holdier Curriculum Vitae (April 2024).pdf
Holdier Curriculum Vitae (April 2024).pdfHoldier Curriculum Vitae (April 2024).pdf
Holdier Curriculum Vitae (April 2024).pdf
 
General Principles of Intellectual Property: Concepts of Intellectual Proper...
General Principles of Intellectual Property: Concepts of Intellectual  Proper...General Principles of Intellectual Property: Concepts of Intellectual  Proper...
General Principles of Intellectual Property: Concepts of Intellectual Proper...
 
How to Give a Domain for a Field in Odoo 17
How to Give a Domain for a Field in Odoo 17How to Give a Domain for a Field in Odoo 17
How to Give a Domain for a Field in Odoo 17
 
Explore beautiful and ugly buildings. Mathematics helps us create beautiful d...
Explore beautiful and ugly buildings. Mathematics helps us create beautiful d...Explore beautiful and ugly buildings. Mathematics helps us create beautiful d...
Explore beautiful and ugly buildings. Mathematics helps us create beautiful d...
 
1029-Danh muc Sach Giao Khoa khoi 6.pdf
1029-Danh muc Sach Giao Khoa khoi  6.pdf1029-Danh muc Sach Giao Khoa khoi  6.pdf
1029-Danh muc Sach Giao Khoa khoi 6.pdf
 
Sociology 101 Demonstration of Learning Exhibit
Sociology 101 Demonstration of Learning ExhibitSociology 101 Demonstration of Learning Exhibit
Sociology 101 Demonstration of Learning Exhibit
 
How to Manage Global Discount in Odoo 17 POS
How to Manage Global Discount in Odoo 17 POSHow to Manage Global Discount in Odoo 17 POS
How to Manage Global Discount in Odoo 17 POS
 
TỔNG ÔN TẬP THI VÀO LỚP 10 MÔN TIẾNG ANH NĂM HỌC 2023 - 2024 CÓ ĐÁP ÁN (NGỮ Â...
TỔNG ÔN TẬP THI VÀO LỚP 10 MÔN TIẾNG ANH NĂM HỌC 2023 - 2024 CÓ ĐÁP ÁN (NGỮ Â...TỔNG ÔN TẬP THI VÀO LỚP 10 MÔN TIẾNG ANH NĂM HỌC 2023 - 2024 CÓ ĐÁP ÁN (NGỮ Â...
TỔNG ÔN TẬP THI VÀO LỚP 10 MÔN TIẾNG ANH NĂM HỌC 2023 - 2024 CÓ ĐÁP ÁN (NGỮ Â...
 
Micro-Scholarship, What it is, How can it help me.pdf
Micro-Scholarship, What it is, How can it help me.pdfMicro-Scholarship, What it is, How can it help me.pdf
Micro-Scholarship, What it is, How can it help me.pdf
 
Activity 01 - Artificial Culture (1).pdf
Activity 01 - Artificial Culture (1).pdfActivity 01 - Artificial Culture (1).pdf
Activity 01 - Artificial Culture (1).pdf
 
The basics of sentences session 3pptx.pptx
The basics of sentences session 3pptx.pptxThe basics of sentences session 3pptx.pptx
The basics of sentences session 3pptx.pptx
 
Basic Civil Engineering first year Notes- Chapter 4 Building.pptx
Basic Civil Engineering first year Notes- Chapter 4 Building.pptxBasic Civil Engineering first year Notes- Chapter 4 Building.pptx
Basic Civil Engineering first year Notes- Chapter 4 Building.pptx
 

Factory method & strategy pattern

  • 1.
  • 2. 2
  • 3. 3  Name: Factory Method  Intent: Define an interface for creating an object, but let subclasses decide which class to instantiate. Defer instantiation to subclasses.  Problem: A class needs to instantiate a derivation of another class, but doesn't know which one. Factory Method allows a derived class to make this decision.  Solution: Provides an abstraction or an interface and lets subclass or implementing classes decide which class or method should be instantiated or called, based on the conditions or parameters given.
  • 4. 4 Product is the interface for the type of object that the Factory Method creates. Creator is the interface that defines the Factory Method.
  • 5. 5  You want to connect to a database but you want to decide at run time which type of database it is (i.e. SQL, Oracle, MySQL etc.)  Apply Factory Method
  • 6. 6
  • 7. 7 public interface ConnectionFactory{ public Connection createConnection(); } class MyConnectionFactory implements ConnectionFactory{ public String type; public MyConnectionFactory(String t){ type = t; } public Connection createConnection(){ if(type.equals("Oracle")){ return new OracleConnection(); } else if(type.equals("SQL")){ return new SQLConnection(); } else{ return new MySQLConnection(); } } }
  • 8. 8 public interface Connection{ public String description(); public void open(); public void close(); } class SQLConnection implements Connection{ public String description(){ return "SQL";} } class MySQLConnection implements Connection{ public String description(){ return "MySQL” ;} } class OracleConnection implements Connection{ public String description(){ return "Oracle"; } } These three implementing classes should have definition for Open & Close Methods of above interface as well to be concrete.
  • 9. 9 class TestConnectionFactory{ public static void main(String[]args){ MyConnectionFactory con = new MyConnectionFactory("My SQL"); Connection con2 = con.createConnection(); System.out.println("Connection Created: "); System.out.println(con2.description()); } }
  • 10. 10
  • 11. 11  Name: Strategy  Intent: Define a family of algorithms, encapsulate each one, and make them interchangeable. Strategy lets the algorithm vary independently from clients that use it.  Problem: How to design for varying, but related, algorithms or policies?  Solution: Define each algorithm/policy/strategy in a separate class, with a common interface.
  • 12. 12
  • 13. 13  Strategy : declares an interface common to all supported algorithms. Context uses this interface to call the algorithm defined by a ConcreteStrategy.  ConcreteStrategy: implements the algorithm using the Strategy interface.  Context : is configured with a ConcreteStrategy object.  maintains a reference to a Strategy object.  may define an interface that lets Strategy access its data.
  • 14. 14  We are developing an e-commerce application where we need to calculate Tax…there are two tax strategies…Tax rate is 10% for old citizens and 15% otherwise.
  • 15. 15
  • 16. 16 public interface TaxStrategy{ public void calcTax(); } class Citizen implements TaxStrategy{ public void calcTax(){ System.out.println("Tax Deduction @ 15%");}} class OldCitizen implements TaxStrategy{ public void calcTax(){ System.out.println("Tax Deduction @ 10%");}}
  • 17. 17 class TaxContext{ private TaxStrategy TS; public void setStrategy(TaxStrategy ts){ TS=ts; } public void calculateTax(){ TS.calcTax(); }} class Client{ public static void main(String[]args){ TaxContext cont = new TaxContext(); cont.setStrategy(new Citizen()); cont.calculateTax(); } }
  • 18. 18  There are different Taxing algorithms or strategies, and they change over time. Who should create the strategy?  A straightforward approach is to apply the Factory pattern
  • 19. 19
  • 20. 20
  • 21. 21 public interface StrategyFactory{ public TaxStrategy getStrategy(); } class MyStrategy implements StrategyFactory{ String type; public MyStrategy(String t){ type=t; } public TaxStrategy getStrategy(){ if(type.equals("Citizen")) return new Citizen(); else return new OldCitizen();} }
  • 22. 22 class Client{ public static void main(String[]args){ MyStrategy m = new MyStrategy("Citizen"); TaxContext cont = new TaxContext(); cont.setStrategy(m.getStrategy()); cont.calculateTax(); } }
  • 23. 23
  • 24. 24  Name: Proxy  Intent: Provide a surrogate or placeholder for another object to control access to it.  Problem: You want to control the access to an object for different reasons. You may want to delay the creation / initialization of expensive objects or you may want to provide a local representation of a remote object.  Solution: Provide a Stub / placeholder for actual object.
  • 25. 25
  • 26. 26  Subject - Interface implemented by the RealSubject and representing its services. The interface must be implemented by the proxy as well so that the proxy can be used in any location where the RealSubject can be used.  Proxy- Maintains a reference that allows the Proxy to access the RealSubject. Implements the same interface implemented by the RealSubject so that the Proxy can be substituted for the RealSubject. Controls access to the RealSubject and may be responsible for its creation and deletion.  RealSubject- the real object that the proxy represents.
  • 27. 27  Consider an image viewer program that lists and displays high resolution photos. The program has to show a list of all photos however it does not need to display the actual photo until the user selects an image item from a list.
  • 28. 28
  • 29. 29 public interface Image{ public void showImage(); } class HRImage implements Image{ public HRImage(){ System.out.println("loading a High Resolution image"); } public void showImage(){ System.out.println("Showing a High Resolution Image"); } }
  • 30. 30 class ProxyImage implements Image{ private Image proxyImage; public ProxyImage(){ System.out.println("Loading a proxy image");} public void showImage(){ proxyImage = (HRImage)new HRImage(); proxyImage.showImage();} } class ImageViewer{ public static void main(String[]args){ Image HRImage1 = new ProxyImage(); Image HRImage2 = new ProxyImage(); Image HRImage3 = new ProxyImage(); HRImage1.showImage();} }
  • 31. 31  Virtual Proxies: delaying the creation and initialization of expensive objects until needed, where the objects are created on demand  Remote Proxies: providing a local representation for an object that is in a different address space. A common example is Java RMI stub objects. The stub object acts as a proxy where invoking methods on the stub would cause the stub to communicate and invoke methods on a remote object (called skeleton) found on a different machine.  Protection Proxies: where a proxy controls access to RealSubject methods, by giving access to some objects while denying access to others.
  • 32. 32