SlideShare a Scribd company logo
1 of 20
1
Iterator, Adapter, Singleton, Flyweight
Design Patterns
2
Design patterns
• Design pattern:
A standard solution to a common software problem in a context.
 describes a recurring software structure or idiom
 is abstract from any particular programming language
 identifies classes and their roles in the solution to a problem
3
Benefits of using patterns
• Patterns give a design common vocabulary for software design:
 Allows engineers to abstract a problem and talk about that abstraction
in isolation from its implementation.
 A culture; domain-specific patterns increase design speed.
• Capture expertise and allow it to be communicated:
 Promotes design reuse and avoid mistakes.
 Makes it easier for other developers to understand a system.
• Improve documentation (less is needed):
 Improve understandability (patterns are described well, once).
4
Gang of Four (GoF) patterns
• Creational Patterns (abstracting the object-instantiation process)
 Factory Method Abstract Factory Singleton
 Builder Prototype
• Structural Patterns (how objects/classes can be combined)
 Adapter Bridge Composite
 Decorator Facade Flyweight
 Proxy
• Behavioral Patterns (communication between objects)
 Command Interpreter Iterator
 Mediator Observer State
 Strategy Chain of Responsibility Visitor
 Template Method
5
Describing a pattern
• In what situation should this pattern be used?
• What should you do? What is the pattern?
 describe details of the objects/classes/structure needed
 should be somewhat language-neutral
• Why is this pattern useful?
• Why might someone not want this pattern?
6
Pattern: Iterator
objects thru’ collections
7
Iterator pattern
• To access all members of a collection, must perform a specialized
traversal for each data structure.
 Introduces undesirable dependences.
 Does not generalize to other collections.
 Provide a standard iterator object supplied by all data structures.
 The implementation performs traversals, does bookkeeping.
• The implementation has knowledge about the representation.
 Results are communicated to clients via a standard interface.
8
Pattern: Adapter
an object that connects with other object via an interface
9
Adapter pattern
• We have an object that contains the functionality we need, but not
in the way we want to use it.
 Cumbersome / unpleasant to use. Prone to bugs.
• Eg.
 We are given an Iterator, but not the collection it came from.
 We want to do a for-each loop over the elements,
but you can't do this with an Iterator, only an Iterable:
public void printAll(Iterator<String> itr) {
// error: must implement Iterable
for (String s : itr) {
System.out.println(s);
} }
10
Adapter in action
• Create an adapter object that bridges the provided and desired
functionality.
public class IterableAdapter implements Iterable<String> {
private Iterator<String> iterator;
public IterableAdapter(Iterator<String> itr) {
this.iterator = itr;
}
public Iterator<String> iterator() {
return iterator;
}
}
...
public void printAll(Iterator<String> itr) {
IterableAdapter adapter = new IterableAdapter(itr);
for (String s : adapter) { ... } // works
}
11
Pattern: Singleton
A class that has only a single instance
12
Creational Patterns
• Constructors in Java are inflexible:
 Can't return a subtype of the class they belong to.
 Always returns a fresh new object; can never re-use one.
• Creational factories:
 Factory method
 Abstract Factory object
 Prototype
 Dependency injection
• Sharing:
 Singleton
 Interning
 Flyweight
13
Restricting object creation
• Sometimes we really only ever need (or want) one instance of a
particular class.
 Examples: keyboard reader, bank data collection, game, UI
 We'd like to make it illegal to have more than one.
• Issues:
 Creating lots of objects can take a lot of time.
 Extra objects take up memory.
 It is a pain to deal with different objects floating around if they are
essentially the same.
 Multiple objects of a type intended to be unique can lead to bugs.
• What happens if we have more than one game UI, or account manager?
14
Singleton pattern
• singleton: An object that is the only object of its type.
(one of the most known / popular design patterns)
 Ensuring that a class has at most one instance.
 Providing a global access point to that instance.
• e.g. Provide an accessor method that allows users to see the instance.
• Benefits:
 Takes responsibility of managing that instance away from the
programmer (illegal to construct more instances).
 Saves memory.
 Avoids bugs arising from multiple instances.
15
Restricting objects
• One way to avoid creating objects: use static methods
 Examples: Math, System
 Is this a good alternative choice? Why or why not?
Disadvantage:
• Lacks flexibility.
 Static methods can't be passed as an argument, nor returned.
• Cannot be extended.
 Example: Static methods can't be subclassed and overridden like an
object's methods could be.
16
• Make constructor(s) private so that they can not be called from
outside by clients.
• Declare a single private static instance of the class.
• Write a public getInstance() or similar method that allows
access to the single instance.
 May need to protect / synchronize this method to ensure that it will
work in a multi-threaded program.
Implementing Singleton
17
Pattern: Flyweight
a class that has only one instance for each unique state
18
Redundant objects
• Problem: Redundant objects can swamp down the system.
 Many objects have the same state.
 example: File objects that represent the same file on disk
•new File(“stud.txt")
•new File(“stud.txt")
•new File(“stud.txt")
...
•new File(“stud.txt")
 example: Date objects that represent the same date of the year
•new Date(1, 21)
•new Date(1, 21)
19
Flyweight pattern
• flyweight: An assurance that no more than one instance of a class
will have identical state.
 Achieved by caching identical instances of objects.
 Similar to singleton, but one instance for each unique object state.
 Useful when there are many instances, but many are equivalent.
 Can be used in conjunction with Factory Method pattern to create a
very efficient object-builder.
 Examples in Java: String, Image, Toolkit, Formatter,
Calendar, JDBC
20
Finally..
• Design patterns don’t solve the problem themselves, they help us
solve the problem
• If you also want to prepare the same dish that tastes good like in
your favorite restaurant then you need to follow the same approach
and techniques given by the experienced chefs.
• The same is the case with design patterns.

More Related Content

Similar to Design_Patterns_Dr.CM.ppt

Most Useful Design Patterns
Most Useful Design PatternsMost Useful Design Patterns
Most Useful Design PatternsSteven Smith
 
UNIT IV DESIGN PATTERNS.pptx
UNIT IV DESIGN PATTERNS.pptxUNIT IV DESIGN PATTERNS.pptx
UNIT IV DESIGN PATTERNS.pptxanguraju1
 
cf.Objective() 2017 - Design patterns - Brad Wood
cf.Objective() 2017 - Design patterns - Brad Woodcf.Objective() 2017 - Design patterns - Brad Wood
cf.Objective() 2017 - Design patterns - Brad WoodOrtus Solutions, Corp
 
Design patterns - Common Solutions to Common Problems - Brad Wood
Design patterns -  Common Solutions to Common Problems - Brad WoodDesign patterns -  Common Solutions to Common Problems - Brad Wood
Design patterns - Common Solutions to Common Problems - Brad WoodOrtus Solutions, Corp
 
P Training Presentation
P Training PresentationP Training Presentation
P Training PresentationGaurav Tyagi
 
Performance Tuning - Memory leaks, Thread deadlocks, JDK tools
Performance Tuning -  Memory leaks, Thread deadlocks, JDK toolsPerformance Tuning -  Memory leaks, Thread deadlocks, JDK tools
Performance Tuning - Memory leaks, Thread deadlocks, JDK toolsHaribabu Nandyal Padmanaban
 
Introduction to design_patterns
Introduction to design_patternsIntroduction to design_patterns
Introduction to design_patternsamitarcade
 
common design patterns summary.pdf
common design patterns summary.pdfcommon design patterns summary.pdf
common design patterns summary.pdfNikolayRaychev2
 
Fundamental Design Patterns.pptx
Fundamental Design Patterns.pptxFundamental Design Patterns.pptx
Fundamental Design Patterns.pptxJUNSHIN8
 
Bartlesville Dot Net User Group Design Patterns
Bartlesville Dot Net User Group Design PatternsBartlesville Dot Net User Group Design Patterns
Bartlesville Dot Net User Group Design PatternsJason Townsend, MBA
 
Design pattern and their application
Design pattern and their applicationDesign pattern and their application
Design pattern and their applicationHiệp Tiến
 
Patterns (contd)Software Development ProcessDesign patte.docx
Patterns (contd)Software Development ProcessDesign patte.docxPatterns (contd)Software Development ProcessDesign patte.docx
Patterns (contd)Software Development ProcessDesign patte.docxdanhaley45372
 
Singleton Design Pattern - Creation Pattern
Singleton Design Pattern - Creation PatternSingleton Design Pattern - Creation Pattern
Singleton Design Pattern - Creation PatternSeerat Malik
 

Similar to Design_Patterns_Dr.CM.ppt (20)

Most Useful Design Patterns
Most Useful Design PatternsMost Useful Design Patterns
Most Useful Design Patterns
 
UNIT IV DESIGN PATTERNS.pptx
UNIT IV DESIGN PATTERNS.pptxUNIT IV DESIGN PATTERNS.pptx
UNIT IV DESIGN PATTERNS.pptx
 
cf.Objective() 2017 - Design patterns - Brad Wood
cf.Objective() 2017 - Design patterns - Brad Woodcf.Objective() 2017 - Design patterns - Brad Wood
cf.Objective() 2017 - Design patterns - Brad Wood
 
Design patterns - Common Solutions to Common Problems - Brad Wood
Design patterns -  Common Solutions to Common Problems - Brad WoodDesign patterns -  Common Solutions to Common Problems - Brad Wood
Design patterns - Common Solutions to Common Problems - Brad Wood
 
P Training Presentation
P Training PresentationP Training Presentation
P Training Presentation
 
Introduction to Design Patterns
Introduction to Design PatternsIntroduction to Design Patterns
Introduction to Design Patterns
 
Design patterns
Design patternsDesign patterns
Design patterns
 
Performance Tuning - Memory leaks, Thread deadlocks, JDK tools
Performance Tuning -  Memory leaks, Thread deadlocks, JDK toolsPerformance Tuning -  Memory leaks, Thread deadlocks, JDK tools
Performance Tuning - Memory leaks, Thread deadlocks, JDK tools
 
Introduction to design_patterns
Introduction to design_patternsIntroduction to design_patterns
Introduction to design_patterns
 
common design patterns summary.pdf
common design patterns summary.pdfcommon design patterns summary.pdf
common design patterns summary.pdf
 
Fundamental Design Patterns.pptx
Fundamental Design Patterns.pptxFundamental Design Patterns.pptx
Fundamental Design Patterns.pptx
 
Design patterns
Design patternsDesign patterns
Design patterns
 
designpatterns-.pdf
designpatterns-.pdfdesignpatterns-.pdf
designpatterns-.pdf
 
Bartlesville Dot Net User Group Design Patterns
Bartlesville Dot Net User Group Design PatternsBartlesville Dot Net User Group Design Patterns
Bartlesville Dot Net User Group Design Patterns
 
Design pattern and their application
Design pattern and their applicationDesign pattern and their application
Design pattern and their application
 
Design pattern
Design patternDesign pattern
Design pattern
 
Patterns (contd)Software Development ProcessDesign patte.docx
Patterns (contd)Software Development ProcessDesign patte.docxPatterns (contd)Software Development ProcessDesign patte.docx
Patterns (contd)Software Development ProcessDesign patte.docx
 
Sda 8
Sda   8Sda   8
Sda 8
 
Design pattern-presentation
Design pattern-presentationDesign pattern-presentation
Design pattern-presentation
 
Singleton Design Pattern - Creation Pattern
Singleton Design Pattern - Creation PatternSingleton Design Pattern - Creation Pattern
Singleton Design Pattern - Creation Pattern
 

Recently uploaded

Full Stack Web Development Course for Beginners
Full Stack Web Development Course  for BeginnersFull Stack Web Development Course  for Beginners
Full Stack Web Development Course for BeginnersSabitha Banu
 
Like-prefer-love -hate+verb+ing & silent letters & citizenship text.pdf
Like-prefer-love -hate+verb+ing & silent letters & citizenship text.pdfLike-prefer-love -hate+verb+ing & silent letters & citizenship text.pdf
Like-prefer-love -hate+verb+ing & silent letters & citizenship text.pdfMr Bounab Samir
 
Painted Grey Ware.pptx, PGW Culture of India
Painted Grey Ware.pptx, PGW Culture of IndiaPainted Grey Ware.pptx, PGW Culture of India
Painted Grey Ware.pptx, PGW Culture of IndiaVirag Sontakke
 
Alper Gobel In Media Res Media Component
Alper Gobel In Media Res Media ComponentAlper Gobel In Media Res Media Component
Alper Gobel In Media Res Media ComponentInMediaRes1
 
DATA STRUCTURE AND ALGORITHM for beginners
DATA STRUCTURE AND ALGORITHM for beginnersDATA STRUCTURE AND ALGORITHM for beginners
DATA STRUCTURE AND ALGORITHM for beginnersSabitha Banu
 
Pharmacognosy Flower 3. Compositae 2023.pdf
Pharmacognosy Flower 3. Compositae 2023.pdfPharmacognosy Flower 3. Compositae 2023.pdf
Pharmacognosy Flower 3. Compositae 2023.pdfMahmoud M. Sallam
 
Meghan Sutherland In Media Res Media Component
Meghan Sutherland In Media Res Media ComponentMeghan Sutherland In Media Res Media Component
Meghan Sutherland In Media Res Media ComponentInMediaRes1
 
ENGLISH 7_Q4_LESSON 2_ Employing a Variety of Strategies for Effective Interp...
ENGLISH 7_Q4_LESSON 2_ Employing a Variety of Strategies for Effective Interp...ENGLISH 7_Q4_LESSON 2_ Employing a Variety of Strategies for Effective Interp...
ENGLISH 7_Q4_LESSON 2_ Employing a Variety of Strategies for Effective Interp...JhezDiaz1
 
Blooming Together_ Growing a Community Garden Worksheet.docx
Blooming Together_ Growing a Community Garden Worksheet.docxBlooming Together_ Growing a Community Garden Worksheet.docx
Blooming Together_ Growing a Community Garden Worksheet.docxUnboundStockton
 
AmericanHighSchoolsprezentacijaoskolama.
AmericanHighSchoolsprezentacijaoskolama.AmericanHighSchoolsprezentacijaoskolama.
AmericanHighSchoolsprezentacijaoskolama.arsicmarija21
 
Enzyme, Pharmaceutical Aids, Miscellaneous Last Part of Chapter no 5th.pdf
Enzyme, Pharmaceutical Aids, Miscellaneous Last Part of Chapter no 5th.pdfEnzyme, Pharmaceutical Aids, Miscellaneous Last Part of Chapter no 5th.pdf
Enzyme, Pharmaceutical Aids, Miscellaneous Last Part of Chapter no 5th.pdfSumit Tiwari
 
Hierarchy of management that covers different levels of management
Hierarchy of management that covers different levels of managementHierarchy of management that covers different levels of management
Hierarchy of management that covers different levels of managementmkooblal
 
How to Configure Email Server in Odoo 17
How to Configure Email Server in Odoo 17How to Configure Email Server in Odoo 17
How to Configure Email Server in Odoo 17Celine George
 
18-04-UA_REPORT_MEDIALITERAСY_INDEX-DM_23-1-final-eng.pdf
18-04-UA_REPORT_MEDIALITERAСY_INDEX-DM_23-1-final-eng.pdf18-04-UA_REPORT_MEDIALITERAСY_INDEX-DM_23-1-final-eng.pdf
18-04-UA_REPORT_MEDIALITERAСY_INDEX-DM_23-1-final-eng.pdfssuser54595a
 
Earth Day Presentation wow hello nice great
Earth Day Presentation wow hello nice greatEarth Day Presentation wow hello nice great
Earth Day Presentation wow hello nice greatYousafMalik24
 
MICROBIOLOGY biochemical test detailed.pptx
MICROBIOLOGY biochemical test detailed.pptxMICROBIOLOGY biochemical test detailed.pptx
MICROBIOLOGY biochemical test detailed.pptxabhijeetpadhi001
 
Historical philosophical, theoretical, and legal foundations of special and i...
Historical philosophical, theoretical, and legal foundations of special and i...Historical philosophical, theoretical, and legal foundations of special and i...
Historical philosophical, theoretical, and legal foundations of special and i...jaredbarbolino94
 

Recently uploaded (20)

Model Call Girl in Bikash Puri Delhi reach out to us at 🔝9953056974🔝
Model Call Girl in Bikash Puri  Delhi reach out to us at 🔝9953056974🔝Model Call Girl in Bikash Puri  Delhi reach out to us at 🔝9953056974🔝
Model Call Girl in Bikash Puri Delhi reach out to us at 🔝9953056974🔝
 
Full Stack Web Development Course for Beginners
Full Stack Web Development Course  for BeginnersFull Stack Web Development Course  for Beginners
Full Stack Web Development Course for Beginners
 
Like-prefer-love -hate+verb+ing & silent letters & citizenship text.pdf
Like-prefer-love -hate+verb+ing & silent letters & citizenship text.pdfLike-prefer-love -hate+verb+ing & silent letters & citizenship text.pdf
Like-prefer-love -hate+verb+ing & silent letters & citizenship text.pdf
 
Painted Grey Ware.pptx, PGW Culture of India
Painted Grey Ware.pptx, PGW Culture of IndiaPainted Grey Ware.pptx, PGW Culture of India
Painted Grey Ware.pptx, PGW Culture of India
 
Alper Gobel In Media Res Media Component
Alper Gobel In Media Res Media ComponentAlper Gobel In Media Res Media Component
Alper Gobel In Media Res Media Component
 
DATA STRUCTURE AND ALGORITHM for beginners
DATA STRUCTURE AND ALGORITHM for beginnersDATA STRUCTURE AND ALGORITHM for beginners
DATA STRUCTURE AND ALGORITHM for beginners
 
Pharmacognosy Flower 3. Compositae 2023.pdf
Pharmacognosy Flower 3. Compositae 2023.pdfPharmacognosy Flower 3. Compositae 2023.pdf
Pharmacognosy Flower 3. Compositae 2023.pdf
 
Meghan Sutherland In Media Res Media Component
Meghan Sutherland In Media Res Media ComponentMeghan Sutherland In Media Res Media Component
Meghan Sutherland In Media Res Media Component
 
ENGLISH 7_Q4_LESSON 2_ Employing a Variety of Strategies for Effective Interp...
ENGLISH 7_Q4_LESSON 2_ Employing a Variety of Strategies for Effective Interp...ENGLISH 7_Q4_LESSON 2_ Employing a Variety of Strategies for Effective Interp...
ENGLISH 7_Q4_LESSON 2_ Employing a Variety of Strategies for Effective Interp...
 
TataKelola dan KamSiber Kecerdasan Buatan v022.pdf
TataKelola dan KamSiber Kecerdasan Buatan v022.pdfTataKelola dan KamSiber Kecerdasan Buatan v022.pdf
TataKelola dan KamSiber Kecerdasan Buatan v022.pdf
 
Blooming Together_ Growing a Community Garden Worksheet.docx
Blooming Together_ Growing a Community Garden Worksheet.docxBlooming Together_ Growing a Community Garden Worksheet.docx
Blooming Together_ Growing a Community Garden Worksheet.docx
 
AmericanHighSchoolsprezentacijaoskolama.
AmericanHighSchoolsprezentacijaoskolama.AmericanHighSchoolsprezentacijaoskolama.
AmericanHighSchoolsprezentacijaoskolama.
 
Enzyme, Pharmaceutical Aids, Miscellaneous Last Part of Chapter no 5th.pdf
Enzyme, Pharmaceutical Aids, Miscellaneous Last Part of Chapter no 5th.pdfEnzyme, Pharmaceutical Aids, Miscellaneous Last Part of Chapter no 5th.pdf
Enzyme, Pharmaceutical Aids, Miscellaneous Last Part of Chapter no 5th.pdf
 
Hierarchy of management that covers different levels of management
Hierarchy of management that covers different levels of managementHierarchy of management that covers different levels of management
Hierarchy of management that covers different levels of management
 
How to Configure Email Server in Odoo 17
How to Configure Email Server in Odoo 17How to Configure Email Server in Odoo 17
How to Configure Email Server in Odoo 17
 
OS-operating systems- ch04 (Threads) ...
OS-operating systems- ch04 (Threads) ...OS-operating systems- ch04 (Threads) ...
OS-operating systems- ch04 (Threads) ...
 
18-04-UA_REPORT_MEDIALITERAСY_INDEX-DM_23-1-final-eng.pdf
18-04-UA_REPORT_MEDIALITERAСY_INDEX-DM_23-1-final-eng.pdf18-04-UA_REPORT_MEDIALITERAСY_INDEX-DM_23-1-final-eng.pdf
18-04-UA_REPORT_MEDIALITERAСY_INDEX-DM_23-1-final-eng.pdf
 
Earth Day Presentation wow hello nice great
Earth Day Presentation wow hello nice greatEarth Day Presentation wow hello nice great
Earth Day Presentation wow hello nice great
 
MICROBIOLOGY biochemical test detailed.pptx
MICROBIOLOGY biochemical test detailed.pptxMICROBIOLOGY biochemical test detailed.pptx
MICROBIOLOGY biochemical test detailed.pptx
 
Historical philosophical, theoretical, and legal foundations of special and i...
Historical philosophical, theoretical, and legal foundations of special and i...Historical philosophical, theoretical, and legal foundations of special and i...
Historical philosophical, theoretical, and legal foundations of special and i...
 

Design_Patterns_Dr.CM.ppt

  • 1. 1 Iterator, Adapter, Singleton, Flyweight Design Patterns
  • 2. 2 Design patterns • Design pattern: A standard solution to a common software problem in a context.  describes a recurring software structure or idiom  is abstract from any particular programming language  identifies classes and their roles in the solution to a problem
  • 3. 3 Benefits of using patterns • Patterns give a design common vocabulary for software design:  Allows engineers to abstract a problem and talk about that abstraction in isolation from its implementation.  A culture; domain-specific patterns increase design speed. • Capture expertise and allow it to be communicated:  Promotes design reuse and avoid mistakes.  Makes it easier for other developers to understand a system. • Improve documentation (less is needed):  Improve understandability (patterns are described well, once).
  • 4. 4 Gang of Four (GoF) patterns • Creational Patterns (abstracting the object-instantiation process)  Factory Method Abstract Factory Singleton  Builder Prototype • Structural Patterns (how objects/classes can be combined)  Adapter Bridge Composite  Decorator Facade Flyweight  Proxy • Behavioral Patterns (communication between objects)  Command Interpreter Iterator  Mediator Observer State  Strategy Chain of Responsibility Visitor  Template Method
  • 5. 5 Describing a pattern • In what situation should this pattern be used? • What should you do? What is the pattern?  describe details of the objects/classes/structure needed  should be somewhat language-neutral • Why is this pattern useful? • Why might someone not want this pattern?
  • 7. 7 Iterator pattern • To access all members of a collection, must perform a specialized traversal for each data structure.  Introduces undesirable dependences.  Does not generalize to other collections.  Provide a standard iterator object supplied by all data structures.  The implementation performs traversals, does bookkeeping. • The implementation has knowledge about the representation.  Results are communicated to clients via a standard interface.
  • 8. 8 Pattern: Adapter an object that connects with other object via an interface
  • 9. 9 Adapter pattern • We have an object that contains the functionality we need, but not in the way we want to use it.  Cumbersome / unpleasant to use. Prone to bugs. • Eg.  We are given an Iterator, but not the collection it came from.  We want to do a for-each loop over the elements, but you can't do this with an Iterator, only an Iterable: public void printAll(Iterator<String> itr) { // error: must implement Iterable for (String s : itr) { System.out.println(s); } }
  • 10. 10 Adapter in action • Create an adapter object that bridges the provided and desired functionality. public class IterableAdapter implements Iterable<String> { private Iterator<String> iterator; public IterableAdapter(Iterator<String> itr) { this.iterator = itr; } public Iterator<String> iterator() { return iterator; } } ... public void printAll(Iterator<String> itr) { IterableAdapter adapter = new IterableAdapter(itr); for (String s : adapter) { ... } // works }
  • 11. 11 Pattern: Singleton A class that has only a single instance
  • 12. 12 Creational Patterns • Constructors in Java are inflexible:  Can't return a subtype of the class they belong to.  Always returns a fresh new object; can never re-use one. • Creational factories:  Factory method  Abstract Factory object  Prototype  Dependency injection • Sharing:  Singleton  Interning  Flyweight
  • 13. 13 Restricting object creation • Sometimes we really only ever need (or want) one instance of a particular class.  Examples: keyboard reader, bank data collection, game, UI  We'd like to make it illegal to have more than one. • Issues:  Creating lots of objects can take a lot of time.  Extra objects take up memory.  It is a pain to deal with different objects floating around if they are essentially the same.  Multiple objects of a type intended to be unique can lead to bugs. • What happens if we have more than one game UI, or account manager?
  • 14. 14 Singleton pattern • singleton: An object that is the only object of its type. (one of the most known / popular design patterns)  Ensuring that a class has at most one instance.  Providing a global access point to that instance. • e.g. Provide an accessor method that allows users to see the instance. • Benefits:  Takes responsibility of managing that instance away from the programmer (illegal to construct more instances).  Saves memory.  Avoids bugs arising from multiple instances.
  • 15. 15 Restricting objects • One way to avoid creating objects: use static methods  Examples: Math, System  Is this a good alternative choice? Why or why not? Disadvantage: • Lacks flexibility.  Static methods can't be passed as an argument, nor returned. • Cannot be extended.  Example: Static methods can't be subclassed and overridden like an object's methods could be.
  • 16. 16 • Make constructor(s) private so that they can not be called from outside by clients. • Declare a single private static instance of the class. • Write a public getInstance() or similar method that allows access to the single instance.  May need to protect / synchronize this method to ensure that it will work in a multi-threaded program. Implementing Singleton
  • 17. 17 Pattern: Flyweight a class that has only one instance for each unique state
  • 18. 18 Redundant objects • Problem: Redundant objects can swamp down the system.  Many objects have the same state.  example: File objects that represent the same file on disk •new File(“stud.txt") •new File(“stud.txt") •new File(“stud.txt") ... •new File(“stud.txt")  example: Date objects that represent the same date of the year •new Date(1, 21) •new Date(1, 21)
  • 19. 19 Flyweight pattern • flyweight: An assurance that no more than one instance of a class will have identical state.  Achieved by caching identical instances of objects.  Similar to singleton, but one instance for each unique object state.  Useful when there are many instances, but many are equivalent.  Can be used in conjunction with Factory Method pattern to create a very efficient object-builder.  Examples in Java: String, Image, Toolkit, Formatter, Calendar, JDBC
  • 20. 20 Finally.. • Design patterns don’t solve the problem themselves, they help us solve the problem • If you also want to prepare the same dish that tastes good like in your favorite restaurant then you need to follow the same approach and techniques given by the experienced chefs. • The same is the case with design patterns.