5. Strategy, Singleton Patterns

Slides:



Advertisements
Similar presentations
Chapter 5: The Singleton Pattern
Advertisements

Jan Ron McFadyen1 Singleton To guarantee that there is at most one instance of a class we can apply the singleton pattern. Singleton Static.
Oct Ron McFadyen1 Singleton To guarantee that there is at most one instance of a class we can apply the singleton pattern. Singleton Static.
George Blank University Lecturer. CS 602 Java and the Web Object Oriented Software Development Using Java Chapter 4.
Patterns Lecture 2. Singleton Ensure a class only has one instance, and provide a global point of access to it.
Spring 2010ACS-3913 Ron McFadyen1 Singleton To guarantee that there is at most one instance of a class we can apply the singleton pattern. Singleton Static.
Design Patterns Ref : Chapter 15 Bennett et al. useful groups of collaborating classes that provide a solution to commonly occuring problems. provide.
Winter 2007ACS-3913 Ron McFadyen1 Singleton To guarantee that there is at most one instance of a class we can apply the singleton pattern. Singleton Static.
Liang, Introduction to Java Programming, Seventh Edition, (c) 2009 Pearson Education, Inc. All rights reserved Chapter 12 Object-Oriented Design.
Singleton Christopher Chiaverini Software Design & Documentation September 18, 2003.
Design Patterns.
ECE 452 / CS 446 / SE464 Design Patterns: Part 2 - Answers A Tutorial By Peter Kim Partially based on the tutorial by Michał Antkiewicz.
Object-Oriented Software Engineering Practical Software Development using UML and Java Chapter 6: Using Design Patterns 1.
Chapter 26 GoF Design Patterns. The Adapter Design Pattern.
Patterns in programming 1. What are patterns? “A design pattern is a general, reusable solution to a commonly occurring problem in software. A design.
The Factory Patterns SE-2811 Dr. Mark L. Hornick 1.
Design Patterns CS 124 Reference: Gamma et al (“Gang-of-4”), Design Patterns.
Design Principle & Patterns by A.Surasit Samaisut Copyrights : All Rights Reserved.
Patterns in programming1. 2 What are patterns? Answers to common design problems. A language used by developers –To discuss answers to design problems.
1 More OO Design Patterns CSC 335: Object-Oriented Programming and Design.
CSE 332: Design Patterns Review: Design Pattern Structure A design pattern has a name –So when someone says “Adapter” you know what they mean –So you can.
The Singleton Pattern SE-2811 Dr. Mark L. Hornick 1.
The Strategy Pattern SE-2811 Dr. Mark L. Hornick 1.
Object-Oriented Software Engineering Practical Software Development using UML and Java Chapter 6: Using Design Patterns.
Design Patterns Software Engineering CS 561. Last Time Introduced design patterns Abstraction-Occurrence General Hierarchy Player-Role.
CS212: Object Oriented Analysis and Design Lecture 38: Design Pattern-II.
Design Patterns Introduction
Design Patterns SE464 Derek Rayside images from NetObjectives.com & Wikipedia.
1 Chapter 5:Design Patterns. 2 What are design pattern?  Schematic description of design solution to recurring problems in software design and,  Reusable.
Introduction to Object-Oriented Programming Lesson 2.
Threads and Singleton. Threads  The JVM allows multiple “threads of execution”  Essentially separate programs running concurrently in one memory space.
Inheritance and Class Hierarchies Chapter 3. Chapter 3: Inheritance and Class Hierarchies2 Chapter Objectives To understand inheritance and how it facilitates.
Singleton Pattern Presented By:- Navaneet Kumar ise
1 More OO Design Patterns CSC 335: Object-Oriented Programming and Design.
Recap Introduction to Inheritance Inheritance in C++ IS-A Relationship Polymorphism in Inheritance Classes in Inheritance Visibility Rules Constructor.
1 Creational Design Patterns CSC 335: Object-Oriented Programming and Design.
Adding Concurrency to a Programming Language Peter A. Buhr and Glen Ditchfield USENIX C++ Technical Conference, Portland, Oregon, U. S. A., August 1992.
1 Creational Design Patterns CSC 335: Object-Oriented Programming and Design.
Slide design: Dr. Mark L. Hornick
Patterns in programming
Design Patterns: MORE Examples
Design Patterns: Brief Examples
Chapter 5:Design Patterns
MPCS – Advanced java Programming
Design Patterns – Chocolate Factory (from Head First Design Patterns)
Week 2, Day 1: The Factory Method Pattern
The Singleton Pattern SE-2811 Dr. Mark L. Hornick.
Chapter 11 Object-Oriented Design
Singleton Pattern Command Pattern
Chapter 6: Using Design Patterns
Objects First with Java
3. Object-oriented Design
SE-2811 Software Component Design
Chapter 22 Object-Oriented Design
Chapter 20 Object-Oriented Analysis and Design
Advanced Java Programming
Singleton Pattern Pattern Name: Singleton Pattern Context
Singleton …there can be only one….
Polymorphism Professor Hugh C. Lauer CS-2303, System Programming Concepts (Slides include materials from The C Programming Language, 2nd edition, by Kernighan.
Chapter 7 –Implementation Issues
SE2811 Software Component Design Dr. Rob Hasker
CS 350 – Software Design Singleton – Chapter 21
9. Threads SE2811 Software Component Design
14. Factory Pattern SE2811 Software Component Design
SE2811 Software Component Design Dr. Rob Hasker
SE-2811 Software Component Design
Design pattern Lecture 6.
14. Factory Pattern SE2811 Software Component Design
CS 325: Software Engineering
GoF Patterns Ch. 26.
Presentation transcript:

5. Strategy, Singleton Patterns SE2811 Software Component Design Dr. Rob Hasker Ch. 22 of Java Design Patterns Reference to “Program to interfaces rather than implementations” in Software Design Principles 5. Strategy, Singleton Patterns

Grassba Goal: automatically mow your lawn Issue: need to support different patterns Classic solution: if statement

But what about more interesting patterns? public class GrassbaDrive { public void move() { step(); if ( blocked() ) { if ( style == STRIP ) turnRight(180); else if ( style == CROSS ) turnRight(90); else turnRight(random(180)); } … But what about more interesting patterns? What if need to store pattern-specific information? What if there are large numbers of patterns?

Solution: write a class public class GrassbaDrive { public MovementBehavior movementStrategy; public GrassbaDrive(MovementBehavior s) { movementStrategy = s; movementStrategy.setDrive(this); } public void move() { step(); is ( isBlocked() ) movementStrategy.turn(); public void turnRight() { … } … public class StripedMovement extends MovementBehavior { … public void turn() { drive.turnRight(180); } Note # indicates an attribute is protected – this is particularly important for the drive

public class CrissCrossMovement extends MovementBehavior { … public void turn() { drive.turnRight(90); } public class RandomMovement extends MovementBehavior { drive.turnright(random(180));

Using the strategies: GrassbaDrive stripedDrive = new GrassbaDrive(new StripedMovement()); GrasbaDrive randDrive = new GrassbaDrive(new RandomMovement()); // recall the GrassbaDrive constructor: public GrassbaDrive(MovementBehavior s) { movementStrategy = s; movementStrategy.setDrive(this); } Need the reference back to the container because the movement will depend on sensors, actuators on the Grassba But needing a reference to the container SIGNIFICANTLY reduces reusability. Why do we need this line? But what problems does it create?

Containers and elements Class Hive { private List<Bee> workers; public void addBee(b) { workers.add(b); } … } class Bee { private Hive myHive; public Bee(Hive h) { myHive = h; } Sensible? Sure: bees live in hives But consider: Bee drone = new Bee(null); Drone (male) bees wander Effectively need new class for bees that are not in a hive General issue: If element has reference to container, can only use with that container This makes reusing the class much harder An example of tight coupling Principle: Avoid having elements refer to their containers Programmers are used to using null for something like a non-existent hive, but it means we are not reflecting the domain! If the distinction is truly important, create drone-specific classes, but then need worker class; maybe the rule “all bees have hives” is getting in the way of development!

Using the strategies: GrassbaDrive stripedDrive = new GrassbaDrive(new StripedMovement()); GrasbaDrive randDrive = new GrassbaDrive(new RandomMovement()); // recall the GrassbaDrive constructor: public GrassbaDrive(MovementBehavior s) { movementStrategy = s; movementStrategy.setDrive(this); } Need the reference back to the container because the movement will depend on sensors, actuators on the Grassba In this case, strategy must be tightly coupled with GrassbaDrive, so rule violation is ok

General form Is there a preference for interfaces over abstract classes? Elements: Context: class that encapsulates, uses specific behavior Strategy: interface that defines the behavior ConcreteStrategy: implements a specific behavior

When to use the Strategy pattern? Strategy pattern: a behavioral pattern Captures run-time behavior Indicator: application requires similar objects whose behavior varies But is there another way to capture the different behavior?

Alternative to Strategy pattern Have an abstract base class with alternatives But what happens if add gas engine/electric motor option?

Alternative to Strategy pattern Have an abstract base class with alternatives But what happens if add gas engine/electric motor option? In general: significant code duplication, too many overrides What is this like with Strategy? Inheritance simpler in some cases, strategy pattern better in others.

Null Object pattern, reconsidered How are the Strategy, Null Object patterns similar? How are they different? A significant part of the course: identify problems and solve those problems using (design) patterns

Exercise Find cases in which the strategy pattern is used in the Java API Especially: JavaFX Create an example where the strategy pattern is useful in Java FX application code

Review Strategy pattern Principle at work: Problem? Solution? Advantages? Consequences? Principle at work: Program to an interface, not an implementation Software Design Principles, Ch. 3 What does this mean in general? Does the Strategy Pattern have more to it than programming to an interface? When did you program to an interface in CS 2852 (Data Structures)?

Singleton Sometimes it is important to have only one instance of a class Examples: Factory (that creates many “product” instances) More on this later! Window manager Event logger The challenge: Ensure that a certain class has only one instance Provide global access to it Singleton: a creational pattern

Question: How can you prevent any instances of a class from being created? Telling programmers, “be good” works for a time, but sooner or later someone will make a mistake… Don’t write it?... Tell programmers, “just don’t create instances”?

Moving towards a solution… Restrict the ability to construct more than one instance of a Singleton class Make the class responsible for keeping track of its one and only instance Provide a global (static) access method

Basic solution public class Singleton { private static Singleton uniqueInstance = new Singleton(); // private constructor cannot be called; // no instances can be created. private Singleton() { } // return the same instance to all callers of this method public static Singleton getInstance() { return uniqueInstance;

Example public class Printer { private static Printer uniqueInstance = new Printer(); private Printer() { } public static getInstance() { return uniqueInstance; } public void write(String text) { System.out.println(text); // or something fancier… }

Important Concepts Why a private constructor? Could you make the constructor protected? Why a private constructor? Instantiating the Singleton class directly: compilation error Only the Singleton class can create instances of itself How can you access the single instance of the Singleton class? getInstance() is a static method, so accessible through the class name Singleton.getInstance() Provides global access to the instance

Alternative model public class Printer { private static Printer uniqueInstance; //= new Printer(); private Printer() { } public static getInstance() { if ( uniqueInstance == null ) uniqueInstance = new Printer(); return uniqueInstance; } public write(String text) { System.out.println(text); Eager initialization “Lazy” initialization – initialize on use

Eager instantiation has pros and cons Global/static objects created whether used or not Created on application load, before call to main() If creating singleton object is resource intensive, get delay on start Example: object establishes a network connection to a remote database server upon creation Not all information may be available at static initialization time Example: the specific file/database/resource that you are connecting to may not be known at application load time Win: static initialization is guaranteed to be “thread-safe” Relevant for GUI apps

Multithreading Threads: sequence of instructions that can run on a processor Example: thread computing locations of polygons on a 3D scene Multithreading Multiple threads, sometimes one per processor Thread A: compute locations of objects on scene Thread B: predict if two objects will collide Advantage: separate processors can run each in parallel Classic application: computing spreadsheet in background Challenge: now have to think of operations happening in parallel

Lazy Singletons and Multithreading Value of uniqueInstance Singleton.getInstance() null if (uniqueInstance == null){ if (uniqueInstance == null) { uniqueInstance = new Singleton() Object 1 return uniqueInstance; Object 2 Will fix later…

Summary Lazy versus eager instantiation Lazy initialization: create instance when needed Eager initialization: instance created at load time, before needed And whether or not it is actually ever accessed Singleton class: encapsulates its sole instance Only one instance, has global access Wins over public, global variables Retain control of the instance Can ensure just a single instance

Patterns of patterns What patterns have we looked at? Null Object, Adapter, Strategy, Singleton Will cover many more Is there a way to organize them? Singleton: based on how objects are created Strategy: how objects behave at run time Adapter: the structure of objects/classes Null Object: doesn’t really fit in any of the 3 primary categories Will look at each of these Common feature: all reduce coupling between classes, increase cohesion within classes Will discuss cohesion, coupling further

Review Strategy Pattern Singleton Pattern Indicator: excessive behavior overrides, code duplication among classes Consequence: allows changing behavior “late” – at runtime Introduces additional classes to maintain Singleton Pattern Indicator: need single instance of a class Consequence: guarantee one instance, globally accessible Multi-threaded applications: must use more complex solution Possible overuse Creational, Behavioral, Structural Design Patterns Reducing coupling, increasing cohesion