Design Patterns 1: Templates Methods, Abstract Factories, Observer/Listener

Size: px
Start display at page:

Download "Design Patterns 1: Templates Methods, Abstract Factories, Observer/Listener"

Transcription

1 1 / 1 Design Patterns 1: Templates Methods, Abstract Factories, Observer/Listener Yoav Goldberg Bar Ilan University

2 Design Patterns 2 / 1

3 3 / 1

4 each pattern describes a problem which occurs over and over again in out environment, and then describes the core of the solution to that problem, in such a way that you can use this solution a million times over and over, without ever doing it the same way twice. Christopher Alexander, GoF, p.2 4 / 1

5 4 / 1 each pattern describes a problem which occurs over and over again in out environment, and then describes the core of the solution to that problem, in such a way that you can use this solution a million times over and over, without ever doing it the same way twice. Christopher Alexander, GoF, p.2 Alexander was an architect who studies ways to improve the process of designing buildings and urban areas.

6 5 / 1 Design Patterns in Software Ways of writing / organizing code to solve specific problems.

7 6 / 1 Each Pattern has Name a concise and meaningful name. Problem what is the problem and context where we would use this pattern? Solution a description of the elements that make up the pattern. Not a concrete design or implementation; rather an abstract description. Consequences the pros and cons of using the pattern.

8 7 / 1 Why we need patterns? Learn from the wisdom of the ages Reuse other people s experience. Establish a shared vocabulary. Make it easier to communicate the design to others. Improve your design process. Naming things shape the way you think about them. Naming things help you discover abstractions and commonalities between situations.

9 8 / 1 Properties of Design Patterns Describes a proven approach to dealing with a common situation in programming / design. Suggest what to do to obtain elegant, modifiable, extensible, flexible & reusable solution. Is independent of a specific language.

10 9 / 1 Patterns vs. Guidelines Guidelines provide general rules of thumb, like: program to an interface, not to an implementation. each class should be responsible for one thing. have low coupling between classes.... Patterns provide concrete solutions often, patterns help you implement the guidelines.

11 10 / 1 Pattern Example Template Method

12 10 / 1 Pattern Example Template Method Define the skeleton of an algorithm in an operation, deferring some steps to subclasses. Template Methods lets subclasses redefine certain steps of an algorithm without changing the algorithm s structure.

13 10 / 1 Pattern Example Template Method Define the skeleton of an algorithm in an operation, deferring some steps to subclasses. Template Methods lets subclasses redefine certain steps of an algorithm without changing the algorithm s structure. We have seen this already!

14 Template Methods Pattern Example public abstract class DiscreteSignalBase { //... public double getvalueat(double x) { if (x < this.firstmeasurementpoint() x > this.lastmeasurementpoint()) { return 0; if (x == this.lastmeasurementpoint()) { return this.yvals[this.xvals.length - 1]; double ans = 0; for (int i = 1; i < this.xvals.length; i++) { double x0 = this.xvals[i - 1]; double x1 = this.xvals[i]; if (x >= x0 && x < x1) { double y0 = this.yvals[i - 1]; double y1 = this.yvals[i]; ans = this.calculatevalueat(x,x0,y0,x1,y1); break; return ans; 11 / 1

15 12 / 1 Template Methods Pattern Example public abstract class DiscreteSignalBase { //... public double getvalueat(double x) { //... ans = this.calculatevalueat(x,x0,y0,x1,y1); //... abstract protected double calculatevalueat( double x, double x0, double y0, double x1, double y1); getvalueat(double x) is a template method! it defines the skeleton of an algorithm, and a certain part of it is redefined in a subclass class.

16 Another Example 13 / 1

17 14 / 1 Consider this collections interface. public interface Collection { boolean isempty(); int size(); void add(comparable o); void remove(comparable o); void addall(collection other); void removeall(collection other); Comparable getsmallest(); Comparable getlargest(); Comparable getithelement(int i); boolean contains(comparable o); boolean containsany(collection other); boolean containsall(collection other);

18 15 / 1 We would like to define the following implementations: A dynamic-size Array Linked List Skip-List Binary Tree

19 15 / 1 We would like to define the following implementations: A dynamic-size Array Linked List Skip-List Binary Tree So much work!

20 public interface Collection { boolean isempty(); int size(); void add(comparable o); void remove(comparable o); void addall(collection other); void removeall(collection other); Comparable getsmallest(); Comparable getlargest(); Comparable getithelement(int i); boolean contains(comparable o); boolean containsany(collection other); boolean containsall(collection other); 16 / 1

21 17 / 1 public interface Collection { boolean isempty(); // derived int size(); void add(comparable o); void remove(comparable o); void addall(collection other); // derived void removeall(collection other); // derived Comparable getsmallest(); // derived Comparable getlargest(); // derived Comparable getithelement(int i); boolean contains(comparable o); // derived? boolean containsany(collection other); // derived boolean containsall(collection other); // derived

22 Perfect for template methods! 18 / 1

23 Perfect for template methods! public abstract class CollectionBase { abstract int size(); abstract void add(comparable o); abstract void remove(comparable o); abstract getithelement(int 0); boolean isempty() { return (this.size() == 0); void addall(collection other) { for (int i = 0; i < other.size(); i++) { this.add(other.getithelement(i));... void removeall(collection other) { for (int i = 0; i < other.size(); i++) { this.remove(other.getithelement(i)); 18 / 1

24 Comparable getlargest() { if (this.isempty()) { return null; Comparable max = this.getithelement(0); for (int i = 1; i < other.size(); i++) { Comparable current = this.getithelement(i); if (current.compareto(max) > 0) { current = max; return max; 19 / 1... Comparable getsmallest() { if (this.isempty()) { return null; Comparable min = this.getithelement(0); for (int i = 1; i < other.size(); i++) { Comparable current = this.getithelement(i); if (current.compareto(min) < 0) { current = min; return min;

25 20 / 1... boolean contains(comparable o) { for (int i = 0; i < this.size(); i++) { if (this.getithelement(i).equals(o)) { return true; return false; boolean containsany(collection other) { for (int i = 0; i < other.size(); i++) { Comparable o = other.getithelement(i); if (this.contains(o)) { return true; return false;...

26 21 / 1... boolean containsall(collection other) { for (int i = 0; i < other.size(); i++) { Comparable o = other.getithelement(i); if (!this.contains(o)) { return false; return true;

27 Implementing a concrete collection: BinaryTree 22 / 1

28 23 / 1 public class BinaryTree extends CollectionBase implements Collection { private Comparable value; private BinaryTree left; private BinaryTree right;... public BinaryTree(Comparable value) { this(value, null, null); public BinaryTree(Comparable v, BinaryTree l, BinaryTree r) { this.value = v; this.left = l; this.right = r; private isleaf() { return (this.left == null && this.right == null);

29 24 / public int size() { ans = 1; if (this.left!= null) { ans += this.left.size(); if (this.right!= null) { ans += this.right.size(); return public void add(comparable c) { if (c.compareto(this.value) < 0) { this.addleft(c); else { this.addright(c);...

30 ... private void addleft(comparable c) { if (this.left == null) { this.left = new BinaryTree(c); else { this.left.add(c); private void addright(comparable c) { public Comparable getithelement(int i) { public void remove(comparable c) { // / 1

31 26 / 1 Template Method Implementing four basic methods in each class. Getting rich collections that use these methods.

32 27 / 1 Design Patterns - benefits of a common vocabulary Instead of saying: We have some shared behavior that is common for all classes, but some operations that are used in these methods are specific for each implementation. So what we did is to create an abstract base class with some abstract methods that are used as place-holders, and we wrote some methods that rely on the abstract methods. Now the deriving class should provide implementation to the abstract methods, and the methods that are using the abstract methods will just work. we can just say: We used the template method pattern

33 Factory Pattern 28 / 1

34 29 / 1 War Cards Game. (Again.)

35 30 / 1 Reminder War Card Game Card Deck Pile Player Dealer WarGameLogic WarGame

36 31 / 1 Requirements Change Different Kinds of Decks A regular Deck (like we already have). A MagiciansDeck with 52 identical cards. Gets the Card value in the constructor. A MessyDeck with 52 random cards (can have duplicates).

37 31 / 1 Requirements Change Different Kinds of Decks A regular Deck (like we already have). A MagiciansDeck with 52 identical cards. Gets the Card value in the constructor. A MessyDeck with 52 random cards (can have duplicates). We know the drill: Make Deck an interface. RegularDeck, MagiciansDeck, MessyDeck all implement Deck. (optional 1): all derive from (extend) Deck (optional 2): all derive from abstract DeckBase

38 31 / 1 Requirements Change Different Kinds of Decks A regular Deck (like we already have). A MagiciansDeck with 52 identical cards. Gets the Card value in the constructor. A MessyDeck with 52 random cards (can have duplicates). We know the drill: Make Deck an interface. RegularDeck, MagiciansDeck, MessyDeck all implement Deck. (optional 1): all derive from (extend) Deck (optional 2): all derive from abstract DeckBase Dealer needs to know which deck to use.

39 31 / 1 Requirements Change Different Kinds of Decks A regular Deck (like we already have). A MagiciansDeck with 52 identical cards. Gets the Card value in the constructor. A MessyDeck with 52 random cards (can have duplicates). We know the drill: Make Deck an interface. RegularDeck, MagiciansDeck, MessyDeck all implement Deck. (optional 1): all derive from (extend) Deck (optional 2): all derive from abstract DeckBase Dealer needs to know which deck to use. pass it on the constructor!

40 32 / 1 Different Kinds of Decks Problem Consider a dealer implementation:

41 32 / 1 Different Kinds of Decks Problem Consider a dealer implementation: public class HalfHalfDealer implements Dealer { public void deal(player p1, Player p2) { Deck deck = new Deck(); deck.shuffle(); // We know that a new deck has 52 cards, an even number. while (!deck.isempty()) { p1.collectcard(deck.taketopcard()); p2.collectcard(deck.taketopcard());

42 Different Kinds of Decks Problem If we move Deck to the constructor: public class HalfHalfDealer implements Dealer { private Deck deck; public HalfHalfDealer(Deck deck) { this.deck = deck; public void deal(player p1, Player p2) { deck.shuffle(); while (!deck.isempty()) { p1.collectcard(deck.taketopcard()); p2.collectcard(deck.taketopcard()); //... public static void main(string[] args) { Deck deck = new MessyDeck(); Dealer dealer = new HalfHalfDealer(deck); dealer.deal(new Player("a"), new Player("b")); dealer.deal(new Player("c"), new Player("d")); 33 / 1

43 Different Kinds of Decks Problem If we move Deck to the constructor: public class HalfHalfDealer implements Dealer { private Deck deck; public HalfHalfDealer(Deck deck) { this.deck = deck; public void deal(player p1, Player p2) { deck.shuffle(); while (!deck.isempty()) { p1.collectcard(deck.taketopcard()); p2.collectcard(deck.taketopcard()); Problem Dealer creates a new Deck in the deal method. the deck is ruined after the dealing is done. We cannot pass the deck on the constructor if we want to run the dealer more than once! 34 / 1

44 35 / 1 Different Kinds of Decks Solution Factory Pattern Provide an interface for creating families of related or dependent objects without specifying their concrete classes.

45 35 / 1 Different Kinds of Decks Solution Factory Pattern Provide an interface for creating families of related or dependent objects without specifying their concrete classes. Encapsulate the creation behavior in its own interface.

46 35 / 1 Different Kinds of Decks Solution Factory Pattern Provide an interface for creating families of related or dependent objects without specifying their concrete classes. Encapsulate the creation behavior in its own interface. public interface DeckFactory { Deck create();

47 36 / 1 Different Kinds of Decks Solution Factory Pattern Provide an interface for creating families of related or dependent objects without specifying their concrete classes.

48 36 / 1 Different Kinds of Decks Solution Factory Pattern Provide an interface for creating families of related or dependent objects without specifying their concrete classes. Encapsulate the creation behavior in its own interface.

49 36 / 1 Different Kinds of Decks Solution Factory Pattern Provide an interface for creating families of related or dependent objects without specifying their concrete classes. Encapsulate the creation behavior in its own interface. public interface DeckFactory { Deck create();

50 37 / 1 Different Kinds of Decks Solution public interface DeckFactory { Deck create();

51 37 / 1 Different Kinds of Decks Solution public interface DeckFactory { Deck create(); public class HalfHalfDealer implements Dealer { private DeckFactory df; public HalfHalfDealer(DeckFactory df) { this.df = df; public void deal(player p1, Player p2) { Deck deck = this.df.create(); deck.shuffle(); while (!deck.isempty()) { p1.collectcard(deck.taketopcard()); p2.collectcard(deck.taketopcard());

52 Different Kinds of Decks Solution public interface DeckFactory { Deck create(); public class HalfHalfDealer implements Dealer { private DeckFactory df; public HalfHalfDealer(DeckFactory df) { this.df = df; public void deal(player p1, Player p2) { Deck deck = this.df.create(); deck.shuffle(); while (!deck.isempty()) { p1.collectcard(deck.taketopcard()); p2.collectcard(deck.taketopcard()); Dealer is creating Decks, but doesn t know which ones. 37 / 1

53 38 / 1 Using the deck factory public static void main(string[] args) { DeckFactory messyfactory = new MessyDeckFactory(); Dealer dealer = new HalfHalfDealer(messyFactory); dealer.deal(new Player("a"), new Player("b")); dealer.deal(new Player("c"), new Player("d"));

54 39 / 1 Deck Factories public class RegularDeckFactory implements DeckFactory { public Deck create() { return new RegularDeck();

55 39 / 1 Deck Factories public class RegularDeckFactory implements DeckFactory { public Deck create() { return new RegularDeck(); public class MessyDeckFactory implements DeckFactory { public Deck create() { return new MessyDeck();

56 40 / 1 Deck Factories public class RegularDeckFactory implements DeckFactory { public Deck create() { return new RegularDeck(); public class MessyDeckFactory implements DeckFactory { public Deck create() { return new MessyDeck(); What about the MagiciansDeck? Remember, it gets a Card at the constructor.... and the DeckFactory interface defines create() without parameters. what can we do? where do we specify the card?

57 41 / 1 Deck Factories public class MagiciansDeckFactory implements DeckFactory { private Card card; public MagiciansDeckFactory(Card c) { this.card = c; public Deck create() { return new MagiciansDeck(this.card);

58 42 / 1 public static void main(string[] args) { Card c = new Card(12, Card.DIAMONDS); DeckFactory factory = new MagiciansDeckFactory(c); Dealer dealer = new HalfHalfDealer(factory); dealer.deal(new Player("a"), new Player("b")); dealer.deal(new Player("c"), new Player("d"));

59 43 / 1 Factory Pattern Decouple the identity of the created class from the class that creates it. Allows class A creates instances of class B, without knowing B s actual type. (Dealer is creating Decks without knowing the Decks types.) This behavior is achieved through an interface which is responsible for the creation behavior.

60 44 / 1 Observer Pattern (also called Listener, EventListener, Publish-subscribe)

61 45 / 1 War Cards Game. (Again.)

62 46 / 1 Requirements Change Need to Collect Statistics Number of turns without a war. Number of turns with a war. Longest number of wars in single turn. Number of turn-wins for each player.

63 46 / 1 Requirements Change Need to Collect Statistics Number of turns without a war. Number of turns with a war. Longest number of wars in single turn. Number of turn-wins for each player. How would you implement this?

64 46 / 1 Requirements Change Need to Collect Statistics Number of turns without a war. Number of turns with a war. Longest number of wars in single turn. Number of turn-wins for each player. How would you implement this? Need to track the statistics. turns and wars take place inside the WarGameLogic class. Add counting variables and accessors to WarGameLogic?

65 47 / 1 public class WarGameLogic { private CardComparator cardcompare; private int numturns; private int numturnswithwars; private int longestwarsequence; private int currentwarlength; private int numwinsplayer1;... public WarGameLogic(CardComparator cardcompare) { this.cardcompare = cardcompare; this.numturns = 0; this.numturnswithwars = 0; this.longestwarsequence = 0; this.numwinsplayer1 = 0;

66 48 / 1 public Player playoneturn(player p1, Player p2) { this.numturns += 1; // new this.currentwarlength = 0; // new Pile pile = new Pile(); Player winner = this.drawcardsandannouncewinner(p1, p2, pile); winner.collectwinningcards(pile); if (winner == p1) { // new this.numwinsplayer1 += 1; // new return winner; private Player drawcardsandannouncewinner(player p1, Player p2,pile pile){ //......

67 49 / 1 private Player dowar(player p1,player p2,pile pile) { this.currentwarlength += 1; if (this.currentwarlength > this.longestwarsequence){ this.longestwarsequence=this.currentwarlength; for (int i = 0; i < 2; ++i) { Card c = p1.playtopcard(); if (c!= null) { pile.addcard(c); //... public int getplayer1wins() { return this.numwinsplayer1; public int getplayer2wins() { return this.numturns - this.numwinsplayer1; //...

68 50 / 1 Not so nice Remember: Each class should be responsible of one thing This is called high cohesion.

69 50 / 1 Not so nice Remember: Each class should be responsible of one thing This is called high cohesion. The WarGameLogic class is doing too much: Handle Logic Track The Statistics

70 50 / 1 Not so nice Remember: Each class should be responsible of one thing This is called high cohesion. The WarGameLogic class is doing too much: Handle Logic Track The Statistics What do we do if the required statistics change? (we also didn t say how we are going to access the data.)

71 50 / 1 Not so nice Remember: Each class should be responsible of one thing This is called high cohesion. The WarGameLogic class is doing too much: Handle Logic Track The Statistics What do we do if the required statistics change? (we also didn t say how we are going to access the data.) Solution Introduce a new StatisticsTracker class. (StatisticsTracker can (should?) be an interface.)

72 51 / 1 public class StatisticsTracker { private int numturns; private int numturnswithwars; private int longestwarsequence; private int currentwarlength; private int numwinsplayer1;... public StatisticsTracker() { this.numturns = 0; this.numturnswithwars = 0; this.longestwarsequence = 0; this.numwinsplayer1 = 0;

73 52 / 1 public void turnstarted() { this.numturns += 1; this.currentwarlength = 0; public void turnended(int winner) { if (winner == 1) { this.numwinsplayer1 += 1; public void warphase() { this.currentwarlength += 1; if (this.currentwarlength > this.longestwarsequence){ this.longestwarsequence=this.currentwarlength; public int getplayer1wins() { return this.numwinsplayer1; //...

74 public class WarGameLogic { private CardComparator cardcompare; private StatisticsTracker stats; public WarGameLogic(CardComparator cardcompare, StatisticsTracker statstracker) { this.cardcompare = cardcompare; this.stats = statstracker; public Player playoneturn(player p1, Player p2) { this.stats.turnstarted(); Pile pile = new Pile(); Player winner = this.drawcardsandannouncewinner(p1, p2, pile); winner.collectwinningcards(pile); int winnernum = winner == p1? 1 : 2; this.stats.turnended(winnernum); return winner; / 1

75 54 / 1 private Player drawcardsandannouncewinner(player p1, Player p2,pile pile){ //... private Player dowar(player p1,player p2,pile pile) { this.stats.warphase(); for (int i = 0; i < 2; ++i) { Card c = p1.playtopcard(); if (c!= null) { pile.addcard(c); //...

76 55 / 1 Solution So Far: The WarGameLogic class holds a StatisticsTracker. WarGameLogic notifies the StatisticsTracker about game events. The StatisticsTracker class tracks the interesting statistics. Advantages We separated (decoupled) the stats-tracking logic from the game-playing logic. Each class is responsible for one thing. Easy to change/replace the tracked statistics without changing the WarGameLogic code.

77 56 / 1 Requirements Change 2 Want to add a narration to the game Print out the game progression: player 1 wins! we have a war! we have another war! and, we have another war! player 2 wins a turn with 3 wars! player 2 wins! player 2 wins again! player 2 wins again! player 2 wins again! player 2 is on a winning streak! player 2 wins again! player 1 wins!... Where would you add this?

78 57 / 1 Adding a narration Implement it in the WarGame or WarGameLogic? NO. As with the statistics, this will result in low-cohesion: the WarGameLogic will be responsible for two things!

79 57 / 1 Adding a narration Implement it in the WarGame or WarGameLogic? NO. As with the statistics, this will result in low-cohesion: the WarGameLogic will be responsible for two things! Implement a GameNarrator class. Like the StatisticsTracker class, the Narrator will receive notifications on game events from the WarGameLogic, and will choose how to display them. (GameNarrator can be an interface.)

80 public class WarGameLogic { private CardComparator cardcompare; private StatisticsTracker stats; private GameNarrator narrator; public WarGameLogic(CardComparator cardcompare, StatisticsTracker statstracker, GameNarrator narrator) { this.cardcompare = cardcompare; this.stats = statstracker; this.narrator = narrator; public Player playoneturn(player p1, Player p2) { this.stats.turnstarted(); this.narrator.turnstarted(); Pile pile = new Pile(); Player winner = this.drawcardsandannouncewinner(p1, p2, pile); winner.collectwinningcards(pile); int winnernum = winner == p1? 1 : 2; this.stats.turnended(winnernum); this.narrator.turnended(winnernum); return winner; 58 / 1

81 59 / 1 Another Requirement Digests WarGames can be very long. We would like to be able to send short summaries every 50 turns. Hello John, since the last update, player 1 won 29 times and player 2 won 21 times. 18 wars took place.

82 59 / 1 Another Requirement Digests WarGames can be very long. We would like to be able to send short summaries every 50 turns. Hello John, since the last update, player 1 won 29 times and player 2 won 21 times. 18 wars took place. Add an DigestCreator class? Yep, this will work.

83 60 / 1 Problems with the approach High Coupling WarGameLogic needs to know about the existence of: StatisticsTracker GameNarrator DigestCreator Any similar class we may add. We have to change the code of WarGameLogic each time. We have High Coupling between the WarGameLogic and the StatisticsTracker, GameNarrator, DigestCreator classes.

84 60 / 1 Problems with the approach High Coupling WarGameLogic needs to know about the existence of: StatisticsTracker GameNarrator DigestCreator Any similar class we may add. We have to change the code of WarGameLogic each time. We have High Coupling between the WarGameLogic and the StatisticsTracker, GameNarrator, DigestCreator classes. Additionally What if we want only Digest but not GameNarrator? What if we want to send Digests to 5 different users? What if a user want to stop receiving notifications?

85 Enters the Observer pattern. 61 / 1

86 62 / 1 The Observer Pattern The Problem being solved An object needs to: Send updates to many different consumers. The set of consumers can change over time. Consumers can ask to not get any more notifications. The object should not care who the consumers are. The consumers can receive messages from many different objects. Terminology: The object sending the notifications is called the observable or subject. The consumers are called observers.

87 63 / 1 The Observer Pattern The Observed object: (WarGameLogic) Defines a common interface that receivers of notifications should implement. ( GameEventListener ) Adds methods to: Add a new receiver. Remove a receiver. Notify all receivers. The Observer objects: (i.e. GameNarrator) Implement the interface. Register themselves with the Observable.

88 64 / 1 Observer Pattern in the War Game public interface GameEventListener { void turnstarted(); void turnended(int winner); void warphase();

89 Observer Pattern in the War Game public class StatisticsTracker implements GameEventListener { private int numturns; private int numturnswithwars; private int longestwarsequence; private int currentwarlength; private int numwinsplayer1; public StatisticsTracker() { this.numturns = 0; this.numturnswithwars = 0; this.longestwarsequence = 0; this.numwinsplayer1 = 0; public void turnstarted() { this.numturns += 1; this.currentwarlength = 0; // / 1

90 Observer Pattern in the War Game public class WarGameLogic { private CardComparator cardcompare; private List<GameEventListener> listeners; public WarGameLogic(CardComparator cardcompare) { this.cardcompare = cardcompare; this.listeners = new ArrayList<GameEventListener>();... public Player playoneturn(player p1, Player p2) { this.notifyturnstarted(); Pile pile = new Pile(); Player winner = this.drawcardsandannouncewinner(p1, p2, pile); winner.collectwinningcards(pile); int winnernum = winner == p1? 1 : 2; this.notifyturnended(winnernum); return winner; 66 / 1

91 Observer Pattern in the War Game public class WarGameLogic { private CardComparator cardcompare; private List<GameEventListener> listeners; public WarGameLogic(CardComparator cardcompare) { this.cardcompare = cardcompare; this.listeners = new ArrayList<GameEventListener>(); public Player playoneturn(player p1, Player p2) { this.notifyturnstarted(); Pile pile = new Pile(); Player winner = this.drawcardsandannouncewinner(p1, p2, pile); winner.collectwinningcards(pile); int winnernum = winner == p1? 1 : 2; this.notifyturnended(winnernum); return winner; 67 / 1

92 Observer Pattern in the War Game public class WarGameLogic { //... public void addlistener(gameeventlistener lst) { this.listeners.add(lst); public void removelistener(gameeventlistener lst) { this.listeners.remove(lst); public void notifyturnstarted() { for (GameEventListener l : this.listeners) { l.turnstarted(); public void notifyturnended(int winner) { for (GameEventListener l : this.listeners) { l.turnended(winner); // / 1

93 69 / 1 Observer Pattern in the War Game WarGameLogic logic = new WarGameLogic(); GameNarrator narrator = new WarGameNarrator(); StatisticsTracker stats = new StatisticsTracker(); DigestCreator 1 = new DigestCreator("John", "john@doe.com"); DigestCreator 2 = new DigestCreator("Jane","jane@darc.com"); logic.addlistener(narrator); logic.addlistener(stats); logic.addlistener( 1); logic.addlistener( 2); //... run the game

94 70 / 1 The Observer Pattern The observed object (WarGameLogic) send messages to 0 or more observers (listeners). Communication is achieved through a shared interface. The observers (or listeners) register themselves with the observed object. The observed object does not care who the receivers are. He just needs to know that: they showed interest in receiving the messages. they are capable of handling them.

95 71 / 1 The Observer Pattern - Advanced Usage Requirement: A game variant in which, every 10 turns, the card comparison rules change. This behavior should stop after the first war event.

96 71 / 1 The Observer Pattern - Advanced Usage Requirement: A game variant in which, every 10 turns, the card comparison rules change. This behavior should stop after the first war event. This can be implemented using the GameEventListener how?

97 72 / 1 public class ComparisonChangeBehavior implements GameEventListener { private WarGameLogic logic; private int turnscounter; public ComparisonChangeBehavior(WarGameLogic logic) { this.logic = logic; this.turnscounter = 0; this.logic.addlistener(this); public void turnstarted() { this.turnscounter+=1; if (turnscounter == 10) { this.logic.setcardcomparator(...); this.turnscounter = 0; public void warphase() { this.logic.removelistener(this); public void turnended(int winner) {

98 73 / 1 The EventListener can know the object it listens to, and can send messages to it based on events. The EventListener can also ask to be removed from the notification list.

99 74 / 1 Summary Design Patterns Suggested solutions for re-occurring situations in software design and organization. Some Specific Patterns Template Method Factory Observer / Listener

CS 231 Data Structures and Algorithms Fall Binary Search Trees Lecture 23 October 29, Prof. Zadia Codabux

CS 231 Data Structures and Algorithms Fall Binary Search Trees Lecture 23 October 29, Prof. Zadia Codabux CS 231 Data Structures and Algorithms Fall 2018 Binary Search Trees Lecture 23 October 29, 2018 Prof. Zadia Codabux 1 Agenda Ternary Operator Binary Search Tree Node based implementation Complexity 2 Administrative

More information

An Introduction to Patterns

An Introduction to Patterns An Introduction to Patterns Robert B. France Colorado State University Robert B. France 1 What is a Pattern? - 1 Work on software development patterns stemmed from work on patterns from building architecture

More information

Ingegneria del Software Corso di Laurea in Informatica per il Management. Design Patterns part 1

Ingegneria del Software Corso di Laurea in Informatica per il Management. Design Patterns part 1 Ingegneria del Software Corso di Laurea in Informatica per il Management Design Patterns part 1 Davide Rossi Dipartimento di Informatica Università di Bologna Pattern Each pattern describes a problem which

More information

More on Design. CSCI 5828: Foundations of Software Engineering Lecture 23 Kenneth M. Anderson

More on Design. CSCI 5828: Foundations of Software Engineering Lecture 23 Kenneth M. Anderson More on Design CSCI 5828: Foundations of Software Engineering Lecture 23 Kenneth M. Anderson Outline Additional Design-Related Topics Design Patterns Singleton Strategy Model View Controller Design by

More information

What is a Pattern? Lecture 40: Design Patterns. Elements of Design Patterns. What are design patterns?

What is a Pattern? Lecture 40: Design Patterns. Elements of Design Patterns. What are design patterns? What is a Pattern? Lecture 40: Design Patterns CS 62 Fall 2017 Kim Bruce & Alexandra Papoutsaki "Each pattern describes a problem which occurs over and over again in our environment, and then describes

More information

CSC207H: Software Design Lecture 6

CSC207H: Software Design Lecture 6 CSC207H: Software Design Lecture 6 Wael Aboelsaadat wael@cs.toronto.edu http://ccnet.utoronto.ca/20075/csc207h1y/ Office: BA 4261 Office hours: R 5-7 Acknowledgement: These slides are based on material

More information

Design Pattern. CMPSC 487 Lecture 10 Topics: Design Patterns: Elements of Reusable Object-Oriented Software (Gamma, et al.)

Design Pattern. CMPSC 487 Lecture 10 Topics: Design Patterns: Elements of Reusable Object-Oriented Software (Gamma, et al.) Design Pattern CMPSC 487 Lecture 10 Topics: Design Patterns: Elements of Reusable Object-Oriented Software (Gamma, et al.) A. Design Pattern Design patterns represent the best practices used by experienced

More information

Design Patterns Reid Holmes

Design Patterns Reid Holmes Material and some slide content from: - Head First Design Patterns Book - GoF Design Patterns Book Design Patterns Reid Holmes GoF design patterns $ %!!!! $ "! # & Pattern vocabulary Shared vocabulary

More information

Trusted Components. Reuse, Contracts and Patterns. Prof. Dr. Bertrand Meyer Dr. Karine Arnout

Trusted Components. Reuse, Contracts and Patterns. Prof. Dr. Bertrand Meyer Dr. Karine Arnout 1 Last update: 2 November 2004 Trusted Components Reuse, Contracts and Patterns Prof. Dr. Bertrand Meyer Dr. Karine Arnout 2 Lecture 5: Design patterns Agenda for today 3 Overview Benefits of patterns

More information

CHAPTER 6: CREATIONAL DESIGN PATTERNS

CHAPTER 6: CREATIONAL DESIGN PATTERNS CHAPTER 6: CREATIONAL DESIGN PATTERNS SESSION I: OVERVIEW OF DESIGN PATTERNS, ABSTRACT FACTORY Software Engineering Design: Theory and Practice by Carlos E. Otero Slides copyright 2012 by Carlos E. Otero

More information

CS 251 Intermediate Programming Methods and Classes

CS 251 Intermediate Programming Methods and Classes CS 251 Intermediate Programming Methods and Classes Brooke Chenoweth University of New Mexico Fall 2018 Methods An operation that can be performed on an object Has return type and parameters Method with

More information

CS 251 Intermediate Programming Methods and More

CS 251 Intermediate Programming Methods and More CS 251 Intermediate Programming Methods and More Brooke Chenoweth University of New Mexico Spring 2018 Methods An operation that can be performed on an object Has return type and parameters Method with

More information

MSO Lecture 12. Wouter Swierstra (adapted by HP) October 26, 2017

MSO Lecture 12. Wouter Swierstra (adapted by HP) October 26, 2017 1 MSO Lecture 12 Wouter Swierstra (adapted by HP) October 26, 2017 2 LAST LECTURE Analysis matrix; Decorator pattern; Model-View-Controller; Observer pattern. 3 THIS LECTURE How to create objects 4 CATEGORIES

More information

An Introduction to Patterns

An Introduction to Patterns An Introduction to Patterns Robert B. France Colorado State University Robert B. France 1 What is a Pattern? Patterns are intended to capture the best available software development experiences in the

More information

Introduction to Design Patterns

Introduction to Design Patterns Dr. Michael Eichberg Software Engineering Department of Computer Science Technische Universität Darmstadt Software Engineering Introduction to Design Patterns (Design) Patterns A pattern describes... Patterns

More information

Introduction to Design Patterns

Introduction to Design Patterns Dr. Michael Eichberg Software Technology Group Department of Computer Science Technische Universität Darmstadt Introduction to Software Engineering Introduction to Design Patterns Patterns 2 PATTERNS A

More information

COURSE 2 DESIGN PATTERNS

COURSE 2 DESIGN PATTERNS COURSE 2 DESIGN PATTERNS CONTENT Fundamental principles of OOP Encapsulation Inheritance Abstractisation Polymorphism [Exception Handling] Fundamental Patterns Inheritance Delegation Interface Abstract

More information

Lecture 13: Design Patterns

Lecture 13: Design Patterns 1 Lecture 13: Design Patterns Kenneth M. Anderson Object-Oriented Analysis and Design CSCI 6448 - Spring Semester, 2005 2 Pattern Resources Pattern Languages of Programming Technical conference on Patterns

More information

Design patterns. Valentina Presutti courtesy of Paolo Ciancarini

Design patterns. Valentina Presutti courtesy of Paolo Ciancarini Design patterns Valentina Presutti courtesy of Paolo Ciancarini Agenda What are design patterns? Catalogues of patterns Languages of patterns Two case studies: design with patterns Software Architectures

More information

OODP Session 4. Web Page: Visiting Hours: Tuesday 17:00 to 19:00

OODP Session 4.   Web Page:   Visiting Hours: Tuesday 17:00 to 19:00 OODP Session 4 Session times PT group 1 Monday 18:00 21:00 room: Malet 403 PT group 2 Thursday 18:00 21:00 room: Malet 407 FT Tuesday 13:30 17:00 room: Malet 404 Email: oded@dcs.bbk.ac.uk Web Page: http://www.dcs.bbk.ac.uk/~oded

More information

Pattern Resources. Lecture 25: Design Patterns. What are Patterns? Design Patterns. Pattern Languages of Programming. The Portland Pattern Repository

Pattern Resources. Lecture 25: Design Patterns. What are Patterns? Design Patterns. Pattern Languages of Programming. The Portland Pattern Repository Pattern Resources Lecture 25: Design Patterns Kenneth M. Anderson Object-Oriented Analysis and Design CSCI 6448 - Spring Semester, 2003 Pattern Languages of Programming Technical conference on Patterns

More information

Inheritance. EEC 521: Software Engineering. Dealing with Change. Polymorphism. Software Design. Changing requirements Code needs to be flexible

Inheritance. EEC 521: Software Engineering. Dealing with Change. Polymorphism. Software Design. Changing requirements Code needs to be flexible Inheritance EEC 521: Software Engineering Software Design Design Patterns: Decoupling Dependencies 10/15/09 EEC 521: Software Engineering 1 Inheritance is the mechanism by which one class can acquire properties/responsibilities

More information

The GoF Design Patterns Reference

The GoF Design Patterns Reference The GoF Design Patterns Reference Version.0 / 0.0.07 / Printed.0.07 Copyright 0-07 wsdesign. All rights reserved. The GoF Design Patterns Reference ii Table of Contents Preface... viii I. Introduction....

More information

Software Engineering - I An Introduction to Software Construction Techniques for Industrial Strength Software

Software Engineering - I An Introduction to Software Construction Techniques for Industrial Strength Software Software Engineering - I An Introduction to Software Construction Techniques for Industrial Strength Software Chapter 9 Introduction to Design Patterns Copy Rights Virtual University of Pakistan 1 Design

More information

Modellistica Medica. Maria Grazia Pia, INFN Genova. Scuola di Specializzazione in Fisica Sanitaria Genova Anno Accademico

Modellistica Medica. Maria Grazia Pia, INFN Genova. Scuola di Specializzazione in Fisica Sanitaria Genova Anno Accademico Modellistica Medica Maria Grazia Pia INFN Genova Scuola di Specializzazione in Fisica Sanitaria Genova Anno Accademico 2002-2003 Lezione 8 OO modeling Design Patterns Introduction Creational Patterns Software

More information

OODP Session 5a. Web Page: Visiting Hours: Tuesday 17:00 to 19:00

OODP Session 5a.   Web Page:  Visiting Hours: Tuesday 17:00 to 19:00 OODP Session 5a Next week: Reading week Session times PT group 1 Monday 18:00 21:00 room: Malet 403 PT group 2 Thursday 18:00 21:00 room: Malet 407 FT Tuesday 13:30 17:00 room: Malet 404 Email: oded@dcs.bbk.ac.uk

More information

Patterns of learning

Patterns of learning Design patterns Patterns of learning Suppose we want to learn how to play chess. First, we need to learn the basic rules. Then we need to learn the basic strategy/ principles (value of pieces, etc.). To

More information

Design Patterns. Gunnar Gotshalks A4-1

Design Patterns. Gunnar Gotshalks A4-1 Design Patterns A4-1 On Design Patterns A design pattern systematically names, explains and evaluates an important and recurring design problem and its solution Good designers know not to solve every problem

More information

CPSC 310 Software Engineering. Lecture 11. Design Patterns

CPSC 310 Software Engineering. Lecture 11. Design Patterns CPSC 310 Software Engineering Lecture 11 Design Patterns Learning Goals Understand what are design patterns, their benefits and their drawbacks For at least the following design patterns: Singleton, Observer,

More information

Singleton Pattern Creational

Singleton Pattern Creational Singleton Pattern Creational Intent» Ensure a class has only one instance» Provide a global point of access Motivation Some classes must only have one instance file system, window manager Applicability»

More information

Foundations of Software Engineering Design Patterns -- Introduction

Foundations of Software Engineering Design Patterns -- Introduction Foundations of Software Engineering Design Patterns -- Introduction Fall 2016 Department of Computer Science Ben-Gurion university Based on slides of: Nurit Gal-oz, Department of Computer Science Ben-Gurion

More information

Design Patterns. Definition of a Design Pattern

Design Patterns. Definition of a Design Pattern Design Patterns Barbara Russo Definition of a Design Pattern A Pattern describes a problem which occurs over and over again in our environment, and then describes the core of the solution to that problem,

More information

Lecture 20: Design Patterns II

Lecture 20: Design Patterns II Lecture 20: Design Patterns II Software System Design and Implementation ITCS/ITIS 6112/8112 001 Fall 2008 Dr. Jamie Payton Department of Computer Science University of North Carolina at Charlotte Nov.

More information

To keep track of this new wrinkle we need some new variables at the Class level:

To keep track of this new wrinkle we need some new variables at the Class level: CS201 Arrays Part II Random Trivia Game Let s refine our trivia game, and say that we would like to randomly select four questions out of all of the questions that we loaded, ask each to the player, output

More information

Lectures 24 and 25 Introduction to Architectural Styles and Design Patterns

Lectures 24 and 25 Introduction to Architectural Styles and Design Patterns Lectures 24 and 25 Introduction to Architectural Styles and Design Patterns Software Engineering ITCS 3155 Fall 2008 Dr. Jamie Payton Department of Computer Science University of North Carolina at Charlotte

More information

Applying Design Patterns to accelerate development of reusable, configurable and portable UVCs. Accellera Systems Initiative 1

Applying Design Patterns to accelerate development of reusable, configurable and portable UVCs. Accellera Systems Initiative 1 Applying Design Patterns to accelerate development of reusable, configurable and portable UVCs. Accellera Systems Initiative 1 About the presenter Paul Kaunds Paul Kaunds is a Verification Consultant at

More information

Introduction to Software Engineering (2+1 SWS) Winter Term 2009 / 2010 Dr. Michael Eichberg Vertretungsprofessur Software Engineering Department of

Introduction to Software Engineering (2+1 SWS) Winter Term 2009 / 2010 Dr. Michael Eichberg Vertretungsprofessur Software Engineering Department of Introduction to Software Engineering (2+1 SWS) Winter Term 2009 / 2010 Dr. Michael Eichberg Vertretungsprofessur Software Engineering Department of Computer Science Technische Universität Darmstadt Dr.

More information

Outline. Design Patterns. Observer Pattern. Definitions & Classifications

Outline. Design Patterns. Observer Pattern. Definitions & Classifications Outline Design Patterns Definitions & Classifications Observer Pattern Intent Motivation Structure Participants Collaborations Consequences Implementation 1 What is a Design Pattern describes a problem

More information

SDC Design patterns GoF

SDC Design patterns GoF SDC Design patterns GoF Design Patterns The design pattern concept can be viewed as an abstraction of imitating useful parts of other software products. The design pattern is a description of communicating

More information

Software and Programming 1

Software and Programming 1 Software and Programming 1 Lab 8: Use of classes, static class variables and methods 1st March 2018 SP1-Lab8-2018.pdf Tobi Brodie (Tobi@dcs.bbk.ac.uk) 1 Lab 8 Objectives Understanding the encapsulation

More information

Design Patterns. "Gang of Four"* Design Patterns. "Gang of Four" Design Patterns. Design Pattern. CS 247: Software Engineering Principles

Design Patterns. Gang of Four* Design Patterns. Gang of Four Design Patterns. Design Pattern. CS 247: Software Engineering Principles CS 247: Software Engineering Principles Design Patterns Reading: Freeman, Robson, Bates, Sierra, Head First Design Patterns, O'Reilly Media, Inc. 2004 Ch Strategy Pattern Ch 7 Adapter and Facade patterns

More information

Goals of Lecture. Lecture 27: OO Design Patterns. Pattern Resources. Design Patterns. Cover OO Design Patterns. Pattern Languages of Programming

Goals of Lecture. Lecture 27: OO Design Patterns. Pattern Resources. Design Patterns. Cover OO Design Patterns. Pattern Languages of Programming Goals of Lecture Lecture 27: OO Design Patterns Cover OO Design Patterns Background Examples Kenneth M. Anderson Object-Oriented Analysis and Design CSCI 6448 - Spring Semester, 2001 April 24, 2001 Kenneth

More information

CS 247: Software Engineering Principles. Design Patterns

CS 247: Software Engineering Principles. Design Patterns CS 247: Software Engineering Principles Design Patterns Reading: Freeman, Robson, Bates, Sierra, Head First Design Patterns, O'Reilly Media, Inc. 2004 Ch 1 Strategy Pattern Ch 7 Adapter and Facade patterns

More information

Design Patterns. Claus Jensen

Design Patterns. Claus Jensen Design Patterns Claus Jensen What is a Design Pattern? A design pattern Abstracts a recurring design structure Distils design experience Promotes reuse of design and code Gives an opportunity to see how

More information

Framework. Set of cooperating classes/interfaces. Example: Swing package is framework for problem domain of GUI programming

Framework. Set of cooperating classes/interfaces. Example: Swing package is framework for problem domain of GUI programming Frameworks 1 Framework Set of cooperating classes/interfaces Structure essential mechanisms of a problem domain Programmer can extend framework classes, creating new functionality Example: Swing package

More information

Patterns. Erich Gamma Richard Helm Ralph Johnson John Vlissides

Patterns. Erich Gamma Richard Helm Ralph Johnson John Vlissides Patterns Patterns Pattern-based engineering: in the field of (building) architecting and other disciplines from 1960 s Some software engineers also started to use the concepts Become widely known in SE

More information

Lecture 19: Introduction to Design Patterns

Lecture 19: Introduction to Design Patterns Lecture 19: Introduction to Design Patterns Software System Design and Implementation ITCS/ITIS 6112/8112 091 Fall 2008 Dr. Jamie Payton Department of Computer Science University of North Carolina at Charlotte

More information

Development and Implementation of Workshop Management System Application to Explore Combing Multiple Design Patterns

Development and Implementation of Workshop Management System Application to Explore Combing Multiple Design Patterns St. Cloud State University therepository at St. Cloud State Culminating Projects in Computer Science and Information Technology Department of Computer Science and Information Technology 5-2015 Development

More information

CSCI-142 Exam 1 Review September 25, 2016 Presented by the RIT Computer Science Community

CSCI-142 Exam 1 Review September 25, 2016 Presented by the RIT Computer Science Community CSCI-12 Exam 1 Review September 25, 2016 Presented by the RIT Computer Science Community http://csc.cs.rit.edu 1. Provide a detailed explanation of what the following code does: 1 public boolean checkstring

More information

Algorithms. Produced by. Eamonn de Leastar

Algorithms. Produced by. Eamonn de Leastar Algorithms Produced by Eamonn de Leastar (edeleastar@wit.ie) Collections ± Collections Architecture ± Definition ± Architecture ± Interfaces ± Collection ± List ± Set ± Map ± Iterator ± Implementations

More information

11/12/12. Objectives DESIGN PATTERNS. Design Pattern. Defined Design Patterns. Applying Design Patterns. Motivating Example

11/12/12. Objectives DESIGN PATTERNS. Design Pattern. Defined Design Patterns. Applying Design Patterns. Motivating Example Objectives Design Patterns Open up Eclipse DESIGN PATTERNS Nov 12, 2012 Sprenkle - CSCI209 1 Nov 12, 2012 Sprenkle - CSCI209 2 Design Pattern General reusable solution to a commonly occurring problem in

More information

be used for more than one use case (for instance, for use cases Create User and Delete User, one can have one UserController, instead of two separate

be used for more than one use case (for instance, for use cases Create User and Delete User, one can have one UserController, instead of two separate UNIT 4 GRASP GRASP: Designing objects with responsibilities Creator Information expert Low Coupling Controller High Cohesion Designing for visibility - Applying GoF design patterns adapter, singleton,

More information

Design Patterns. An introduction

Design Patterns. An introduction Design Patterns An introduction Introduction Designing object-oriented software is hard, and designing reusable object-oriented software is even harder. Your design should be specific to the problem at

More information

What is Design Patterns?

What is Design Patterns? Paweł Zajączkowski What is Design Patterns? 1. Design patterns may be said as a set of probable solutions for a particular problem which is tested to work best in certain situations. 2. In other words,

More information

CS 520 Theory and Practice of Software Engineering Fall 2018

CS 520 Theory and Practice of Software Engineering Fall 2018 Today CS 520 Theory and Practice of Software Engineering Fall 208 Object Oriented Design Patterns Recap: Object oriented design principles Design problems & potential solutions Design patterns: What is

More information

Introduction to Design Patterns

Introduction to Design Patterns Introduction to Design Patterns First, what s a design pattern? a general reusable solution to a commonly occurring problem within a given context in software design It s not a finished design that can

More information

Practice Problems. Review, with SOME solutions

Practice Problems. Review, with SOME solutions Practice Problems Review, with SOME solutions Multiple Choice 1. Select the best functional requirement from the list of requirements below. a) A warning dialog should pop up if the student s assignment

More information

CS342: Software Design. Oct 9, 2017

CS342: Software Design. Oct 9, 2017 CS342: Software Design Oct 9, 2017 Outline Facade pattern Observer pattern Homework 1 classes Human player replaces a card 1. Main UserPlayer 2. Main ->CardPile 3. CardPile -> Card -> Main 4. Main

More information

Design Patterns. CSC207 Fall 2017

Design Patterns. CSC207 Fall 2017 Design Patterns CSC207 Fall 2017 Design Patterns A design pattern is a general description of the solution to a well-established problem using an arrangement of classes and objects. Patterns describe the

More information

Lecture 5: Implementing Lists, Version 1

Lecture 5: Implementing Lists, Version 1 CS18 Integrated Introduction to Computer Science Fisler, Nelson Lecture 5: Implementing Lists, Version 1 Contents 1 Implementing Lists 1 2 Methods 2 2.1 isempty...........................................

More information

CPSC 310: Sample Final Exam Study Questions 2014S1 (These are in addition to the Study Questions listed at the end of some lectures)

CPSC 310: Sample Final Exam Study Questions 2014S1 (These are in addition to the Study Questions listed at the end of some lectures) CPSC 310: Sample Final Exam Study Questions 2014S1 (These are in addition to the Study Questions listed at the end of some lectures) 1. Select the best functional requirement from the list of requirements

More information

CS/CE 2336 Computer Science II

CS/CE 2336 Computer Science II CS/CE 2336 Computer Science II UT D Session 20 Design Patterns An Overview 2 History Architect Christopher Alexander coined the term "pattern" circa 1977-1979 Kent Beck and Ward Cunningham, OOPSLA'87 used

More information

Software Design Patterns. Background 1. Background 2. Jonathan I. Maletic, Ph.D.

Software Design Patterns. Background 1. Background 2. Jonathan I. Maletic, Ph.D. Software Design Patterns Jonathan I. Maletic, Ph.D. Department of Computer Science Kent State University J. Maletic 1 Background 1 Search for recurring successful designs emergent designs from practice

More information

CHAPTER 6: CREATIONAL DESIGN PATTERNS

CHAPTER 6: CREATIONAL DESIGN PATTERNS CHAPTER 6: CREATIONAL DESIGN PATTERNS SESSION III: BUILDER, PROTOTYPE, SINGLETON Software Engineering Design: Theory and Practice by Carlos E. Otero Slides copyright 2012 by Carlos E. Otero For non-profit

More information

CSC7203 : Advanced Object Oriented Development. J Paul Gibson, D311. Design Patterns

CSC7203 : Advanced Object Oriented Development. J Paul Gibson, D311. Design Patterns CSC7203 : Advanced Object Oriented Development J Paul Gibson, D311 paul.gibson@telecom-sudparis.eu http://www-public.tem-tsp.eu/~gibson/teaching/csc7203/ Design Patterns /~gibson/teaching/csc7203/csc7203-advancedoo-l2.pdf

More information

Chapter 6 Introduction to Defining Classes

Chapter 6 Introduction to Defining Classes Introduction to Defining Classes Fundamentals of Java: AP Computer Science Essentials, 4th Edition 1 Objectives Design and implement a simple class from user requirements. Organize a program in terms of

More information

2. JAVA OOP R E F E R E N C E : O B J E C T O R I E N T E D D E S I G N A N D P R O G R A M M I N G ( H O R S T M A N N )

2. JAVA OOP R E F E R E N C E : O B J E C T O R I E N T E D D E S I G N A N D P R O G R A M M I N G ( H O R S T M A N N ) 2. JAVA OOP R E F E R E N C E : O B J E C T O R I E N T E D D E S I G N A N D P R O G R A M M I N G ( H O R S T M A N N ) REVIEW + VOCABULARY A class is a blueprint for a new type You define how all instances

More information

CS 151. Binary Trees. Friday, October 5, 12

CS 151. Binary Trees. Friday, October 5, 12 CS 151 Binary Trees 1 Binary Tree Examples Without telling you what a binary tree is, here are some examples (that I will draw on the board): The dots/circles are called nodes, or vertices (singular: one

More information

DESIGN PATTERNS FOR MERE MORTALS

DESIGN PATTERNS FOR MERE MORTALS DESIGN PATTERNS FOR MERE MORTALS Philip Japikse (@skimedic) skimedic@outlook.com www.skimedic.com/blog Microsoft MVP, ASPInsider, MCSD, MCDBA, CSM, CSP Consultant, Teacher, Writer Phil.About() Consultant,

More information

Ingegneria del Software Corso di Laurea in Informatica per il Management. Design Patterns part 1

Ingegneria del Software Corso di Laurea in Informatica per il Management. Design Patterns part 1 Ingegneria del Software Corso di Laurea in Informatica per il Management Design Patterns part 1 Davide Rossi Dipartimento di Informatica Università di Bologna Pattern Each pattern describes a problem which

More information

CS201 - Assignment 3, Part 2 Due: Wednesday March 5, at the beginning of class

CS201 - Assignment 3, Part 2 Due: Wednesday March 5, at the beginning of class CS201 - Assignment 3, Part 2 Due: Wednesday March 5, at the beginning of class For this assignment we will be developing a text-based Tic Tac Toe game 1. The key to this assignment is that we re going

More information

Design to interfaces. Favor composition over inheritance Find what varies and encapsulate it

Design to interfaces. Favor composition over inheritance Find what varies and encapsulate it Design Patterns The Gang of Four suggests a few strategies for creating good o-o designs, including Façade Design to interfaces. Favor composition over inheritance Find what varies and encapsulate it One

More information

GRASP Design Patterns A.A. 2018/2019

GRASP Design Patterns A.A. 2018/2019 GRASP Design Patterns A.A. 2018/2019 Objectives Introducing design patterns Introduzione ai design pattern Designing objects and responsibilities GRASP design patterns A long corridor A passage room Does

More information

CS 370 Design Heuristics D R. M I C H A E L J. R E A L E F A L L

CS 370 Design Heuristics D R. M I C H A E L J. R E A L E F A L L CS 370 Design Heuristics D R. M I C H A E L J. R E A L E F A L L 2 0 1 5 Introduction Now we ll talk about ways of thinking about design Guidelines for trials in trial and errors Major Design Heuristics

More information

INTERNAL ASSESSMENT TEST III Answer Schema

INTERNAL ASSESSMENT TEST III Answer Schema INTERNAL ASSESSMENT TEST III Answer Schema Subject& Code: Object-Oriented Modeling and Design (15CS551) Sem: V ISE (A & B) Q. No. Questions Marks 1. a. Ans Explain the steps or iterations involved in object

More information

The Strategy Pattern Design Principle: Design Principle: Design Principle:

The Strategy Pattern Design Principle: Design Principle: Design Principle: Strategy Pattern The Strategy Pattern defines a family of algorithms, encapsulates each one, and makes them interchangeable. Strategy lets the algorithm vary independently from clients that use it. Design

More information

Define an object that encapsulates how a set of objects interact.

Define an object that encapsulates how a set of objects interact. MEDIATOR Presented By: Mallampati Bhava Chaitanya Intent Define an object that encapsulates how a set of objects interact. Mediator promotes loose coupling by keeping objects from referring to each other

More information

Tuesday, October 4. Announcements

Tuesday, October 4. Announcements Tuesday, October 4 Announcements www.singularsource.net Donate to my short story contest UCI Delta Sigma Pi Accepts business and ICS students See Facebook page for details Slide 2 1 Design Patterns Design

More information

Object-Oriented Design

Object-Oriented Design Object-Oriented Design Lecture 20 GoF Design Patterns Behavioral Department of Computer Engineering Sharif University of Technology 1 GoF Behavioral Patterns Class Class Interpreter: Given a language,

More information

Design Patterns. State. Oliver Haase

Design Patterns. State. Oliver Haase Design Patterns State Oliver Haase 1 Description Object based behavioral pattern Purpose: Allow an object to alter its behavior when its internal state changes. The object will appear to change its class.

More information

The Singleton Pattern. Design Patterns In Java Bob Tarr

The Singleton Pattern. Design Patterns In Java Bob Tarr The Singleton Pattern Intent Ensure a class only has one instance, and provide a global point of access to it Motivation Sometimes we want just a single instance of a class to exist in the system For example,

More information

Coordination Patterns

Coordination Patterns Coordination Patterns 1. Coordination Patterns Design Patterns and their relevance for Coordination Oscar Nierstrasz Software Composition Group Institut für Informatik (IAM) Universität Bern oscar@iam.unibe.ch

More information

CS 151. Binary Search Trees. Wednesday, October 10, 12

CS 151. Binary Search Trees. Wednesday, October 10, 12 CS 151 Binary Search Trees 1 Binary Search Tree A binary search tree stores comparable elements in a binary tree such that for every node r all nodes in the left BST are

More information

Object Design with GoF Patterns, continued. Curt Clifton Rose-Hulman Institute of Technology

Object Design with GoF Patterns, continued. Curt Clifton Rose-Hulman Institute of Technology Object Design with GoF Patterns, continued Curt Clifton Rose-Hulman Institute of Technology Applying Patterns to NextGen POS Iteration 3 Local caching Used Adapter and Factory Failover to local services

More information

Lecture 15 Summary 3/11/2009. By the end of this lecture, you will be able to use different types of Collections and Maps in your Java code.

Lecture 15 Summary 3/11/2009. By the end of this lecture, you will be able to use different types of Collections and Maps in your Java code. Lecture 15 Summary Collections Framework Iterable, Collections, Set Map Collections class Comparable and Comparator By the end of this lecture, you will be able to use different types of Collections and

More information

Design Patterns גרא וייס המחלקה למדעי המחשב אוניברסיטת בן-גוריון

Design Patterns גרא וייס המחלקה למדעי המחשב אוניברסיטת בן-גוריון Design Patterns גרא וייס המחלקה למדעי המחשב אוניברסיטת בן-גוריון 2 Problem: Reusability in OO Designing OO software is hard, and designing reusable OO software is even harder: Software should be specific

More information

Computer Science II Fall 2009

Computer Science II Fall 2009 Name: Computer Science II Fall 2009 Exam #2 Closed book and notes. This exam should have five problems and six pages. Problem 0: [1 point] On a scale of 0 5, where 5 is highest, I think I deserve a for

More information

CS251 Software Engineering Lectures 18: Intro to DP

CS251 Software Engineering Lectures 18: Intro to DP و ابتغ فيما آتاك هللا الدار اآلخرة و ال تنس نصيبك من الدنيا CS251 Software Engineering Lectures 18: Intro to DP Slides by Rick Mercer, Christian Ratliff, Oscar Nierstrasz and others 1 Outline Introduction

More information

Patterns. Giovanni Sakti. in Software Engineering. Starqle

Patterns. Giovanni Sakti. in Software Engineering. Starqle Patterns in Software Engineering Giovanni Sakti Starqle What is Patterns? Patterns Patterns describes a problem, which occurs over and over again in our environment and then desribes the core of the solution

More information

Compsci 290/Mobile, Java

Compsci 290/Mobile, Java Compsci 290/Mobile, Java Owen Astrachan Landon Cox January 16, 2018 1/16/2018 Mobile 290, Spring 2018, Java 1 Java Classes and Objects Class encapsulates state and behavior State is typically private Android

More information

Java Fundamentals (II)

Java Fundamentals (II) Chair of Software Engineering Languages in Depth Series: Java Programming Prof. Dr. Bertrand Meyer Java Fundamentals (II) Marco Piccioni static imports Introduced in 5.0 Imported static members of a class

More information

Software Design COSC 4353/6353 D R. R A J S I N G H

Software Design COSC 4353/6353 D R. R A J S I N G H Software Design COSC 4353/6353 D R. R A J S I N G H Creational Design Patterns What are creational design patterns? Types Examples Structure Effects Creational Patterns Design patterns that deal with object

More information

Object-Oriented Design

Object-Oriented Design Object-Oriented Design Lecturer: Raman Ramsin Lecture 20: GoF Design Patterns Creational 1 Software Patterns Software Patterns support reuse of software architecture and design. Patterns capture the static

More information

Class and Functions. Reusable codes

Class and Functions. Reusable codes Class and Functions Reusable codes Object Oriented Design First concept of object oriented programming is emerged at 60 s. Smalltalk language which is introduced at 1972 was first object oriented programming

More information

Binghamton University. CS-140 Fall Problem Solving. Creating a class from scratch

Binghamton University. CS-140 Fall Problem Solving. Creating a class from scratch Problem Solving Creating a class from scratch 1 Recipe for Writing a Class 1. Write the class boilerplate stuff 2. Declare Fields 3. Write Creator(s) 4. Write accessor methods 5. Write mutator methods

More information

CS 520 Theory and Practice of Software Engineering Fall 2017

CS 520 Theory and Practice of Software Engineering Fall 2017 CS 520 Theory and Practice of Software Engineering Fall 2017 OO design patterns September 28, 2017 Logistics Homework 1 deadline: 10/17/2017. Paper reading 1 (Practical guide to statistical tests) deadline:

More information

APCS Semester #1 Final Exam Practice Problems

APCS Semester #1 Final Exam Practice Problems Name: Date: Per: AP Computer Science, Mr. Ferraro APCS Semester #1 Final Exam Practice Problems The problems here are to get you thinking about topics we ve visited thus far in preparation for the semester

More information

Collections, Maps and Generics

Collections, Maps and Generics Collections API Collections, Maps and Generics You've already used ArrayList for exercises from the previous semester, but ArrayList is just one part of much larger Collections API that Java provides.

More information

M301: Software Systems & their Development. Unit 4: Inheritance, Composition and Polymorphism

M301: Software Systems & their Development. Unit 4: Inheritance, Composition and Polymorphism Block 1: Introduction to Java Unit 4: Inheritance, Composition and Polymorphism Aims of the unit: Study and use the Java mechanisms that support reuse, in particular, inheritance and composition; Analyze

More information

Introduction to Object Oriented Programming. (Hebrew University, CS / Spring 2012 )

Introduction to Object Oriented Programming. (Hebrew University, CS / Spring 2012 ) Introduction to Object Oriented Programming (Hebrew University, CS 67125 / Spring 2012 ) Overview There are many important Object Oriented Design (OOD) principles Today we'll focus on several basic principles

More information