Week 4 (OO Design Principle)
Design Principle 3
Identify aspects of your code that varies and encapsulate and separate it from code that stays the same, so that it won’t affect your real code.
Another way to think about this principle: take the parts that vary and encapsulate them, so that later you can alter or extend the parts that vary without affecting those that don’t.
Design Principle 4
Program to an interface , not to an implementation
Design Principle 5: Hallywood Principle
Don’t call us, we’ll call you
Provides us a way to reduce software rot
The high-level components give the lowlevel components a “don’t call us, we’ll call you’ treatment, i.e., allow low-level components to hook themselves into a system, but the high-level components decide “when” and “how” they are needed
Design Pattern
- Design pattern: in software engineering, a design pattern is a general repeatable solution to a commonly occurring problem in software design.
- Represents a template for how to solve a problem
- Capture design expertise and enables this knowledge to be transferred and reused
- Is not a finished solution, they give you general solutions to design problems
Strategy Pattern
This pattern defines a family of algorithms, encapsulates each one
Strategy pattern is a behaviour design pattern that lets the algorithms vary independently from the context class using it
- This allows you to encapsulate a family of algorithms
- Enables you to “change behaviour” at run-time
Benefits: Uses composition over inheritance which allows better decoupling between the behaviour and context class that uses the behaviour
Drawbacks:
- increase the number of object.
- client must be aware of different strategies
Examples:
- Sorting a list (QuickSort, Bubble Sort, merge sort)
- Encapsulate each sort algorithm into a concrete strategy class
- Context class decides at run-time, which sorting behaviour is needed
- Search (Binary search, DFS, BFS, A*)
State Pattern
This pattern allows an object to alter its behaviour when its internal state changes. The object will appear to change its class.
Example:
First we set up a context for our mp3 player:
Now we’ll create our state interface:
And finally, creating a state for Standby and for Playing:
Template Method Pattern
The Template Method pattern is a behavioural design pattern that defines the skeleton of an algorithm in a method deferring some steps to sub-classes. The template method lets sub-classes redefine certain steps of an algorithm without changing the algorithm structure
Create an abstract class with a template method being final:
Create concrete classes extending the above class:
Cricket.java:
Football.java:
TemplatePatternDemo.java: