SlideShare una empresa de Scribd logo
1 de 51
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
33
 Name: Chain of Responsibility
 Intent: Avoid coupling the sender of a request to its
receiver by giving more than one object a chance to
handle the request. Chain the receiving objects and
pass the request along the chain until an object
handles it.
 Problem: A group of classes each have processes to run
in turn, but there is no way to directly determine in
which class order each should run its process
 Solution: Use a chained association of classes that have
interdependence on each other to define the order of
operations
34
35
 Handler defines an interface for handling requests.
 ConcreteHandler handles requests it is responsible
for.
 can access its successor.
 if the ConcreteHandler can handle the request, it does
so; otherwise it forwards the request to its successor.
36
 We want to develop a Help System for a Bank. The
client can get Help about Accounts, Credit / Debit
Cards, Bank Loan etc.
37
38
interface HelpInterface{
public void getHelp(int id);
}
class AccountHelp implements HelpInterface{
final int ACCOUNT_HELP=1;
HelpInterface successor;
public AccountHelp(HelpInterface s){ successor=s; }
public void getHelp(int id){
if(id!=ACCOUNT_HELP)
successor.getHelp(id);
else
System.out.println("Account Help..."); } }
39
class CardHelp implements HelpInterface{
final int CARD_HELP=2;
HelpInterface successor;
public CardHelp(HelpInterface s){ successor=s; }
public void getHelp(int id){
if(id!=CARD_HELP) successor.getHelp(id);
else System.out.println("Card Help...");}}
class LoanHelp implements HelpInterface{
final int LOAN_HELP=3;
HelpInterface successor;
public LoanHelp(HelpInterface s){ successor=s; }
public void getHelp(int id){
if(id!=LOAN_HELP) successor.getHelp(id);
else System.out.println("Loan Help..."); } }
40
class GenHelp implements HelpInterface{
public GenHelp(){ }
public void getHelp(int id){
System.out.println("General Help...");} }
class Client{
public static void main(String[]args){
GenHelp gh = new GenHelp();
LoanHelp lh = new LoanHelp(gh);
CardHelp ch = new CardHelp(lh);
AccountHelp ah = new AccountHelp(ch);
ah.getHelp(3);
}
}
41
42
 Name: Memento
 Intent: Without violating encapsulation, capture and
externalize an object's internal state so that the object
can be restored to this state later.
 Problem: A class needs to have its internal state
captured and then restored without violating the
class’s encapsulation
 Solution: Use a memento and a caretaker to capture
and store the object’s state
43
 Memento: stores internal state of the Originator
object. The memento may store as much or as little of
the originator's internal state as necessary at its
originator's discretion.
 Originator: creates a memento containing a snapshot
of its current internal state. uses the memento to
restore its internal state.
 Caretaker: is responsible for the memento's
safekeeping. never operates on or examines the
contents of a memento.
44
45
 We want to develop a Simple Calculator that can
restore previous calculations.
46
47
public class Calculator{
int num1,num2,Result;
String operation;
public Calculator(int x, int y,String op){
num1 = x; num2 = y; operation = op;
}
int getResult(){
if(operation=="add") Result = num1+num2;
else if(operation=="sub") Result = num1-num2;
else Result = num1*num2;
return Result;
}
Memento createMemento(){
return new Memento(num1,num2,Result,operation); } }
48
class Memento{
int num1,num2,Result;
String operation;
public Memento(){}
public Memento(int n1,int n2, int r, String op){
num1=n1;
num2=n2;
Result=r;
operation=op;
}
}
49
class CareTaker{
List undo; int i; Memento m;
public CareTaker(){
undo = new ArrayList();
m = new Memento();}
public void addMemento(Memento mem){ undo.add(i,mem); i++; }
public void previous(){
if (undo.size() > 0) {
int ct = undo.size()-1;
m = (Memento)undo.get(ct);
undo.remove(ct);
}
System.out.println("num1: "+m.num1);
System.out.println("num2: "+m.num2);
System.out.println("Result: "+m.Result);
System.out.println("Operation: "+m.operation); } }
50
class Client{
public static void main(String[]args){
CareTaker ct = new CareTaker();
Calculator cal = new Calculator(4,5,"add");
System.out.println("Result is: "+ cal.getResult());
ct.addMemento(cal.createMemento());
cal = new Calculator(80,55,"sub");
System.out.println("Result is: "+ cal.getResult());
ct.addMemento(cal.createMemento());
System.out.println("Last two Calculations are: n");
ct.previous();
ct.previous();
}
}
51

Más contenido relacionado

La actualidad más candente

Sofwear deasign and need of design pattern
Sofwear deasign and need of design patternSofwear deasign and need of design pattern
Sofwear deasign and need of design patternchetankane
 
Strategy Design Pattern
Strategy Design PatternStrategy Design Pattern
Strategy Design PatternGanesh Kolhe
 
M03 1 Structuraldiagrams
M03 1 StructuraldiagramsM03 1 Structuraldiagrams
M03 1 StructuraldiagramsDang Tuan
 

La actualidad más candente (8)

06 inheritance
06 inheritance06 inheritance
06 inheritance
 
Sofwear deasign and need of design pattern
Sofwear deasign and need of design patternSofwear deasign and need of design pattern
Sofwear deasign and need of design pattern
 
Strategy Design Pattern
Strategy Design PatternStrategy Design Pattern
Strategy Design Pattern
 
Composite design pattern
Composite design patternComposite design pattern
Composite design pattern
 
M03 1 Structuraldiagrams
M03 1 StructuraldiagramsM03 1 Structuraldiagrams
M03 1 Structuraldiagrams
 
Design patterns
Design patternsDesign patterns
Design patterns
 
Java: GUI
Java: GUIJava: GUI
Java: GUI
 
Skillwise Struts.x
Skillwise Struts.xSkillwise Struts.x
Skillwise Struts.x
 

Destacado

PostgreSQL Database Slides
PostgreSQL Database SlidesPostgreSQL Database Slides
PostgreSQL Database Slidesmetsarin
 
Design Pattern - Factory Method Pattern
Design Pattern - Factory Method PatternDesign Pattern - Factory Method Pattern
Design Pattern - Factory Method PatternMudasir Qazi
 
Introduction to un supervised learning
Introduction to un supervised learningIntroduction to un supervised learning
Introduction to un supervised learningRishikesh .
 
Approximation algorithms
Approximation algorithmsApproximation algorithms
Approximation algorithmsGanesh Solanke
 
Introduction to Approximation Algorithms
Introduction to Approximation AlgorithmsIntroduction to Approximation Algorithms
Introduction to Approximation AlgorithmsJhoirene Clemente
 
Semi-Supervised Learning
Semi-Supervised LearningSemi-Supervised Learning
Semi-Supervised LearningLukas Tencer
 
Presentation on supervised learning
Presentation on supervised learningPresentation on supervised learning
Presentation on supervised learningTonmoy Bhagawati
 
[Dl輪読会]semi supervised learning with context-conditional generative adversari...
[Dl輪読会]semi supervised learning with context-conditional generative adversari...[Dl輪読会]semi supervised learning with context-conditional generative adversari...
[Dl輪読会]semi supervised learning with context-conditional generative adversari...Deep Learning JP
 
Concept Mapping... for the slightly confused
Concept Mapping... for the slightly confusedConcept Mapping... for the slightly confused
Concept Mapping... for the slightly confusedguestcc23f8a
 
Design Patterns - Factory Method & Abstract Factory
Design Patterns - Factory Method & Abstract FactoryDesign Patterns - Factory Method & Abstract Factory
Design Patterns - Factory Method & Abstract FactoryGuillermo Daniel Salazar
 
Introduction to Concept Mapping
Introduction to Concept MappingIntroduction to Concept Mapping
Introduction to Concept MappingJames Neill
 

Destacado (17)

PostgreSQL Database Slides
PostgreSQL Database SlidesPostgreSQL Database Slides
PostgreSQL Database Slides
 
Really Big Elephants: PostgreSQL DW
Really Big Elephants: PostgreSQL DWReally Big Elephants: PostgreSQL DW
Really Big Elephants: PostgreSQL DW
 
Design Pattern - Factory Method Pattern
Design Pattern - Factory Method PatternDesign Pattern - Factory Method Pattern
Design Pattern - Factory Method Pattern
 
Introduction to un supervised learning
Introduction to un supervised learningIntroduction to un supervised learning
Introduction to un supervised learning
 
Approximation Algorithms
Approximation AlgorithmsApproximation Algorithms
Approximation Algorithms
 
Dentistry and oral health - Develop your search using a Concept Map
Dentistry and oral health - Develop your search using a Concept MapDentistry and oral health - Develop your search using a Concept Map
Dentistry and oral health - Develop your search using a Concept Map
 
Sql Antipatterns Strike Back
Sql Antipatterns Strike BackSql Antipatterns Strike Back
Sql Antipatterns Strike Back
 
Approximation algorithms
Approximation algorithmsApproximation algorithms
Approximation algorithms
 
Introduction to Approximation Algorithms
Introduction to Approximation AlgorithmsIntroduction to Approximation Algorithms
Introduction to Approximation Algorithms
 
Semi-Supervised Learning
Semi-Supervised LearningSemi-Supervised Learning
Semi-Supervised Learning
 
Presentation on supervised learning
Presentation on supervised learningPresentation on supervised learning
Presentation on supervised learning
 
[Dl輪読会]semi supervised learning with context-conditional generative adversari...
[Dl輪読会]semi supervised learning with context-conditional generative adversari...[Dl輪読会]semi supervised learning with context-conditional generative adversari...
[Dl輪読会]semi supervised learning with context-conditional generative adversari...
 
Concept Mapping... for the slightly confused
Concept Mapping... for the slightly confusedConcept Mapping... for the slightly confused
Concept Mapping... for the slightly confused
 
Teaching science using concept maps
Teaching science using concept maps  Teaching science using concept maps
Teaching science using concept maps
 
Design Patterns - Factory Method & Abstract Factory
Design Patterns - Factory Method & Abstract FactoryDesign Patterns - Factory Method & Abstract Factory
Design Patterns - Factory Method & Abstract Factory
 
Introduction to Concept Mapping
Introduction to Concept MappingIntroduction to Concept Mapping
Introduction to Concept Mapping
 
10 Ridiculous Hacks to 5X Click-Through Rates
10 Ridiculous Hacks to 5X Click-Through Rates 10 Ridiculous Hacks to 5X Click-Through Rates
10 Ridiculous Hacks to 5X Click-Through Rates
 

Similar a Factory method, strategy pattern & chain of responsibilities

1. Mini seminar intro
1. Mini seminar intro1. Mini seminar intro
1. Mini seminar introLeonid Maslov
 
lecture10-patterns.ppt
lecture10-patterns.pptlecture10-patterns.ppt
lecture10-patterns.pptAnkitPangasa1
 
lecture10-patterns.ppt
lecture10-patterns.pptlecture10-patterns.ppt
lecture10-patterns.pptbryafaissal
 
Proxy design pattern (Class Ambassador)
Proxy design pattern (Class Ambassador)Proxy design pattern (Class Ambassador)
Proxy design pattern (Class Ambassador)Sameer Rathoud
 
Proxy & adapter pattern
Proxy & adapter patternProxy & adapter pattern
Proxy & adapter patternbabak danyal
 
Structural pattern 3
Structural pattern 3Structural pattern 3
Structural pattern 3Naga Muruga
 
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
 
C# Advanced L07-Design Patterns
C# Advanced L07-Design PatternsC# Advanced L07-Design Patterns
C# Advanced L07-Design PatternsMohammad Shaker
 
Design patterns through java
Design patterns through javaDesign patterns through java
Design patterns through javaAditya Bhuyan
 
Creational pattern 2
Creational pattern 2Creational pattern 2
Creational pattern 2Naga Muruga
 
Observer & singleton pattern
Observer  & singleton patternObserver  & singleton pattern
Observer & singleton patternbabak danyal
 
Java design patterns
Java design patternsJava design patterns
Java design patternsShawn Brito
 
Working Effectively With Legacy Code
Working Effectively With Legacy CodeWorking Effectively With Legacy Code
Working Effectively With Legacy CodeNaresh Jain
 

Similar a Factory method, strategy pattern & chain of responsibilities (20)

Design pattern-presentation
Design pattern-presentationDesign pattern-presentation
Design pattern-presentation
 
Design Patterns
Design PatternsDesign Patterns
Design Patterns
 
1. Mini seminar intro
1. Mini seminar intro1. Mini seminar intro
1. Mini seminar intro
 
lecture10-patterns.ppt
lecture10-patterns.pptlecture10-patterns.ppt
lecture10-patterns.ppt
 
lecture10-patterns.ppt
lecture10-patterns.pptlecture10-patterns.ppt
lecture10-patterns.ppt
 
Proxy design pattern (Class Ambassador)
Proxy design pattern (Class Ambassador)Proxy design pattern (Class Ambassador)
Proxy design pattern (Class Ambassador)
 
Proxy & adapter pattern
Proxy & adapter patternProxy & adapter pattern
Proxy & adapter pattern
 
Structural pattern 3
Structural pattern 3Structural pattern 3
Structural pattern 3
 
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
 
C# Advanced L07-Design Patterns
C# Advanced L07-Design PatternsC# Advanced L07-Design Patterns
C# Advanced L07-Design Patterns
 
Working with Servlets
Working with ServletsWorking with Servlets
Working with Servlets
 
Design patterns through java
Design patterns through javaDesign patterns through java
Design patterns through java
 
Creational pattern 2
Creational pattern 2Creational pattern 2
Creational pattern 2
 
Intake 37 4
Intake 37 4Intake 37 4
Intake 37 4
 
Observer & singleton pattern
Observer  & singleton patternObserver  & singleton pattern
Observer & singleton pattern
 
Java design patterns
Java design patternsJava design patterns
Java design patterns
 
Proxy design pattern
Proxy design patternProxy design pattern
Proxy design pattern
 
Deployment
DeploymentDeployment
Deployment
 
Eclipse Tricks
Eclipse TricksEclipse Tricks
Eclipse Tricks
 
Working Effectively With Legacy Code
Working Effectively With Legacy CodeWorking Effectively With Legacy Code
Working Effectively With Legacy Code
 

Más 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
 

Más 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
 

Último

Expanded definition: technical and operational
Expanded definition: technical and operationalExpanded definition: technical and operational
Expanded definition: technical and operationalssuser3e220a
 
Reading and Writing Skills 11 quarter 4 melc 1
Reading and Writing Skills 11 quarter 4 melc 1Reading and Writing Skills 11 quarter 4 melc 1
Reading and Writing Skills 11 quarter 4 melc 1GloryAnnCastre1
 
Narcotic and Non Narcotic Analgesic..pdf
Narcotic and Non Narcotic Analgesic..pdfNarcotic and Non Narcotic Analgesic..pdf
Narcotic and Non Narcotic Analgesic..pdfPrerana Jadhav
 
Concurrency Control in Database Management system
Concurrency Control in Database Management systemConcurrency Control in Database Management system
Concurrency Control in Database Management systemChristalin Nelson
 
Grade 9 Quarter 4 Dll Grade 9 Quarter 4 DLL.pdf
Grade 9 Quarter 4 Dll Grade 9 Quarter 4 DLL.pdfGrade 9 Quarter 4 Dll Grade 9 Quarter 4 DLL.pdf
Grade 9 Quarter 4 Dll Grade 9 Quarter 4 DLL.pdfJemuel Francisco
 
ESP 4-EDITED.pdfmmcncncncmcmmnmnmncnmncmnnjvnnv
ESP 4-EDITED.pdfmmcncncncmcmmnmnmncnmncmnnjvnnvESP 4-EDITED.pdfmmcncncncmcmmnmnmncnmncmnnjvnnv
ESP 4-EDITED.pdfmmcncncncmcmmnmnmncnmncmnnjvnnvRicaMaeCastro1
 
Q4-PPT-Music9_Lesson-1-Romantic-Opera.pptx
Q4-PPT-Music9_Lesson-1-Romantic-Opera.pptxQ4-PPT-Music9_Lesson-1-Romantic-Opera.pptx
Q4-PPT-Music9_Lesson-1-Romantic-Opera.pptxlancelewisportillo
 
4.16.24 21st Century Movements for Black Lives.pptx
4.16.24 21st Century Movements for Black Lives.pptx4.16.24 21st Century Movements for Black Lives.pptx
4.16.24 21st Century Movements for Black Lives.pptxmary850239
 
Grade Three -ELLNA-REVIEWER-ENGLISH.pptx
Grade Three -ELLNA-REVIEWER-ENGLISH.pptxGrade Three -ELLNA-REVIEWER-ENGLISH.pptx
Grade Three -ELLNA-REVIEWER-ENGLISH.pptxkarenfajardo43
 
Visit to a blind student's school🧑‍🦯🧑‍🦯(community medicine)
Visit to a blind student's school🧑‍🦯🧑‍🦯(community medicine)Visit to a blind student's school🧑‍🦯🧑‍🦯(community medicine)
Visit to a blind student's school🧑‍🦯🧑‍🦯(community medicine)lakshayb543
 
31 ĐỀ THI THỬ VÀO LỚP 10 - TIẾNG ANH - FORM MỚI 2025 - 40 CÂU HỎI - BÙI VĂN V...
31 ĐỀ THI THỬ VÀO LỚP 10 - TIẾNG ANH - FORM MỚI 2025 - 40 CÂU HỎI - BÙI VĂN V...31 ĐỀ THI THỬ VÀO LỚP 10 - TIẾNG ANH - FORM MỚI 2025 - 40 CÂU HỎI - BÙI VĂN V...
31 ĐỀ THI THỬ VÀO LỚP 10 - TIẾNG ANH - FORM MỚI 2025 - 40 CÂU HỎI - BÙI VĂN V...Nguyen Thanh Tu Collection
 
Student Profile Sample - We help schools to connect the data they have, with ...
Student Profile Sample - We help schools to connect the data they have, with ...Student Profile Sample - We help schools to connect the data they have, with ...
Student Profile Sample - We help schools to connect the data they have, with ...Seán Kennedy
 
Daily Lesson Plan in Mathematics Quarter 4
Daily Lesson Plan in Mathematics Quarter 4Daily Lesson Plan in Mathematics Quarter 4
Daily Lesson Plan in Mathematics Quarter 4JOYLYNSAMANIEGO
 
Scientific Writing :Research Discourse
Scientific  Writing :Research  DiscourseScientific  Writing :Research  Discourse
Scientific Writing :Research DiscourseAnita GoswamiGiri
 
ROLES IN A STAGE PRODUCTION in arts.pptx
ROLES IN A STAGE PRODUCTION in arts.pptxROLES IN A STAGE PRODUCTION in arts.pptx
ROLES IN A STAGE PRODUCTION in arts.pptxVanesaIglesias10
 
How to Fix XML SyntaxError in Odoo the 17
How to Fix XML SyntaxError in Odoo the 17How to Fix XML SyntaxError in Odoo the 17
How to Fix XML SyntaxError in Odoo the 17Celine George
 
Man or Manufactured_ Redefining Humanity Through Biopunk Narratives.pptx
Man or Manufactured_ Redefining Humanity Through Biopunk Narratives.pptxMan or Manufactured_ Redefining Humanity Through Biopunk Narratives.pptx
Man or Manufactured_ Redefining Humanity Through Biopunk Narratives.pptxDhatriParmar
 
Active Learning Strategies (in short ALS).pdf
Active Learning Strategies (in short ALS).pdfActive Learning Strategies (in short ALS).pdf
Active Learning Strategies (in short ALS).pdfPatidar M
 

Último (20)

Expanded definition: technical and operational
Expanded definition: technical and operationalExpanded definition: technical and operational
Expanded definition: technical and operational
 
Paradigm shift in nursing research by RS MEHTA
Paradigm shift in nursing research by RS MEHTAParadigm shift in nursing research by RS MEHTA
Paradigm shift in nursing research by RS MEHTA
 
Reading and Writing Skills 11 quarter 4 melc 1
Reading and Writing Skills 11 quarter 4 melc 1Reading and Writing Skills 11 quarter 4 melc 1
Reading and Writing Skills 11 quarter 4 melc 1
 
Narcotic and Non Narcotic Analgesic..pdf
Narcotic and Non Narcotic Analgesic..pdfNarcotic and Non Narcotic Analgesic..pdf
Narcotic and Non Narcotic Analgesic..pdf
 
Concurrency Control in Database Management system
Concurrency Control in Database Management systemConcurrency Control in Database Management system
Concurrency Control in Database Management system
 
Grade 9 Quarter 4 Dll Grade 9 Quarter 4 DLL.pdf
Grade 9 Quarter 4 Dll Grade 9 Quarter 4 DLL.pdfGrade 9 Quarter 4 Dll Grade 9 Quarter 4 DLL.pdf
Grade 9 Quarter 4 Dll Grade 9 Quarter 4 DLL.pdf
 
ESP 4-EDITED.pdfmmcncncncmcmmnmnmncnmncmnnjvnnv
ESP 4-EDITED.pdfmmcncncncmcmmnmnmncnmncmnnjvnnvESP 4-EDITED.pdfmmcncncncmcmmnmnmncnmncmnnjvnnv
ESP 4-EDITED.pdfmmcncncncmcmmnmnmncnmncmnnjvnnv
 
Q4-PPT-Music9_Lesson-1-Romantic-Opera.pptx
Q4-PPT-Music9_Lesson-1-Romantic-Opera.pptxQ4-PPT-Music9_Lesson-1-Romantic-Opera.pptx
Q4-PPT-Music9_Lesson-1-Romantic-Opera.pptx
 
4.16.24 21st Century Movements for Black Lives.pptx
4.16.24 21st Century Movements for Black Lives.pptx4.16.24 21st Century Movements for Black Lives.pptx
4.16.24 21st Century Movements for Black Lives.pptx
 
Grade Three -ELLNA-REVIEWER-ENGLISH.pptx
Grade Three -ELLNA-REVIEWER-ENGLISH.pptxGrade Three -ELLNA-REVIEWER-ENGLISH.pptx
Grade Three -ELLNA-REVIEWER-ENGLISH.pptx
 
Visit to a blind student's school🧑‍🦯🧑‍🦯(community medicine)
Visit to a blind student's school🧑‍🦯🧑‍🦯(community medicine)Visit to a blind student's school🧑‍🦯🧑‍🦯(community medicine)
Visit to a blind student's school🧑‍🦯🧑‍🦯(community medicine)
 
31 ĐỀ THI THỬ VÀO LỚP 10 - TIẾNG ANH - FORM MỚI 2025 - 40 CÂU HỎI - BÙI VĂN V...
31 ĐỀ THI THỬ VÀO LỚP 10 - TIẾNG ANH - FORM MỚI 2025 - 40 CÂU HỎI - BÙI VĂN V...31 ĐỀ THI THỬ VÀO LỚP 10 - TIẾNG ANH - FORM MỚI 2025 - 40 CÂU HỎI - BÙI VĂN V...
31 ĐỀ THI THỬ VÀO LỚP 10 - TIẾNG ANH - FORM MỚI 2025 - 40 CÂU HỎI - BÙI VĂN V...
 
Student Profile Sample - We help schools to connect the data they have, with ...
Student Profile Sample - We help schools to connect the data they have, with ...Student Profile Sample - We help schools to connect the data they have, with ...
Student Profile Sample - We help schools to connect the data they have, with ...
 
Faculty Profile prashantha K EEE dept Sri Sairam college of Engineering
Faculty Profile prashantha K EEE dept Sri Sairam college of EngineeringFaculty Profile prashantha K EEE dept Sri Sairam college of Engineering
Faculty Profile prashantha K EEE dept Sri Sairam college of Engineering
 
Daily Lesson Plan in Mathematics Quarter 4
Daily Lesson Plan in Mathematics Quarter 4Daily Lesson Plan in Mathematics Quarter 4
Daily Lesson Plan in Mathematics Quarter 4
 
Scientific Writing :Research Discourse
Scientific  Writing :Research  DiscourseScientific  Writing :Research  Discourse
Scientific Writing :Research Discourse
 
ROLES IN A STAGE PRODUCTION in arts.pptx
ROLES IN A STAGE PRODUCTION in arts.pptxROLES IN A STAGE PRODUCTION in arts.pptx
ROLES IN A STAGE PRODUCTION in arts.pptx
 
How to Fix XML SyntaxError in Odoo the 17
How to Fix XML SyntaxError in Odoo the 17How to Fix XML SyntaxError in Odoo the 17
How to Fix XML SyntaxError in Odoo the 17
 
Man or Manufactured_ Redefining Humanity Through Biopunk Narratives.pptx
Man or Manufactured_ Redefining Humanity Through Biopunk Narratives.pptxMan or Manufactured_ Redefining Humanity Through Biopunk Narratives.pptx
Man or Manufactured_ Redefining Humanity Through Biopunk Narratives.pptx
 
Active Learning Strategies (in short ALS).pdf
Active Learning Strategies (in short ALS).pdfActive Learning Strategies (in short ALS).pdf
Active Learning Strategies (in short ALS).pdf
 

Factory method, strategy pattern & chain of responsibilities

  • 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
  • 33. 33  Name: Chain of Responsibility  Intent: Avoid coupling the sender of a request to its receiver by giving more than one object a chance to handle the request. Chain the receiving objects and pass the request along the chain until an object handles it.  Problem: A group of classes each have processes to run in turn, but there is no way to directly determine in which class order each should run its process  Solution: Use a chained association of classes that have interdependence on each other to define the order of operations
  • 34. 34
  • 35. 35  Handler defines an interface for handling requests.  ConcreteHandler handles requests it is responsible for.  can access its successor.  if the ConcreteHandler can handle the request, it does so; otherwise it forwards the request to its successor.
  • 36. 36  We want to develop a Help System for a Bank. The client can get Help about Accounts, Credit / Debit Cards, Bank Loan etc.
  • 37. 37
  • 38. 38 interface HelpInterface{ public void getHelp(int id); } class AccountHelp implements HelpInterface{ final int ACCOUNT_HELP=1; HelpInterface successor; public AccountHelp(HelpInterface s){ successor=s; } public void getHelp(int id){ if(id!=ACCOUNT_HELP) successor.getHelp(id); else System.out.println("Account Help..."); } }
  • 39. 39 class CardHelp implements HelpInterface{ final int CARD_HELP=2; HelpInterface successor; public CardHelp(HelpInterface s){ successor=s; } public void getHelp(int id){ if(id!=CARD_HELP) successor.getHelp(id); else System.out.println("Card Help...");}} class LoanHelp implements HelpInterface{ final int LOAN_HELP=3; HelpInterface successor; public LoanHelp(HelpInterface s){ successor=s; } public void getHelp(int id){ if(id!=LOAN_HELP) successor.getHelp(id); else System.out.println("Loan Help..."); } }
  • 40. 40 class GenHelp implements HelpInterface{ public GenHelp(){ } public void getHelp(int id){ System.out.println("General Help...");} } class Client{ public static void main(String[]args){ GenHelp gh = new GenHelp(); LoanHelp lh = new LoanHelp(gh); CardHelp ch = new CardHelp(lh); AccountHelp ah = new AccountHelp(ch); ah.getHelp(3); } }
  • 41. 41
  • 42. 42  Name: Memento  Intent: Without violating encapsulation, capture and externalize an object's internal state so that the object can be restored to this state later.  Problem: A class needs to have its internal state captured and then restored without violating the class’s encapsulation  Solution: Use a memento and a caretaker to capture and store the object’s state
  • 43. 43  Memento: stores internal state of the Originator object. The memento may store as much or as little of the originator's internal state as necessary at its originator's discretion.  Originator: creates a memento containing a snapshot of its current internal state. uses the memento to restore its internal state.  Caretaker: is responsible for the memento's safekeeping. never operates on or examines the contents of a memento.
  • 44. 44
  • 45. 45  We want to develop a Simple Calculator that can restore previous calculations.
  • 46. 46
  • 47. 47 public class Calculator{ int num1,num2,Result; String operation; public Calculator(int x, int y,String op){ num1 = x; num2 = y; operation = op; } int getResult(){ if(operation=="add") Result = num1+num2; else if(operation=="sub") Result = num1-num2; else Result = num1*num2; return Result; } Memento createMemento(){ return new Memento(num1,num2,Result,operation); } }
  • 48. 48 class Memento{ int num1,num2,Result; String operation; public Memento(){} public Memento(int n1,int n2, int r, String op){ num1=n1; num2=n2; Result=r; operation=op; } }
  • 49. 49 class CareTaker{ List undo; int i; Memento m; public CareTaker(){ undo = new ArrayList(); m = new Memento();} public void addMemento(Memento mem){ undo.add(i,mem); i++; } public void previous(){ if (undo.size() > 0) { int ct = undo.size()-1; m = (Memento)undo.get(ct); undo.remove(ct); } System.out.println("num1: "+m.num1); System.out.println("num2: "+m.num2); System.out.println("Result: "+m.Result); System.out.println("Operation: "+m.operation); } }
  • 50. 50 class Client{ public static void main(String[]args){ CareTaker ct = new CareTaker(); Calculator cal = new Calculator(4,5,"add"); System.out.println("Result is: "+ cal.getResult()); ct.addMemento(cal.createMemento()); cal = new Calculator(80,55,"sub"); System.out.println("Result is: "+ cal.getResult()); ct.addMemento(cal.createMemento()); System.out.println("Last two Calculations are: n"); ct.previous(); ct.previous(); } }
  • 51. 51