Design Principle
Design Principle
(Chapter 3) from
Dive Into DESIGN PATTERNS
1
Encapsulation on Method Level (before)
2
Encapsulation on Method Level
(after)
3
Encapsulation: class level (before)
4
Encapsulation: class level (after)
5
Interface is Better than Implementation
6
Diamond Problem in Multiple Inheritance
7
Example of Tight Coupling
8
Getting rid of tight coupling
9
SOLID Design Principles
Changeability
Maintainability
Testability and easier
debugging
11
Open/Closed Principle: Classes should be open for extension but closed for modification
12
The idea was that
once completed, the
implementation of a
class could only be
modified to correct
errors;
new or changed
features would
require that a
different class be
created.
13
public class Rectangle
{
public double Width { get; set; }
public double Height { get; set; }
}
return area;
}
}
14
Add Circle
return area;
} 15
Add Ellipse, Triangle, …?
public abstract class Shape
{
public abstract double Area();
}
public class Rectangle : Shape
{
public double Width { get; set; }
public double Height { get; set; }
public override double Area()
{
return Width*Height;
}
}
public class Circle : Shape
{
public double Radius { get; set; }
public override double Area()
{
return Radius*Radius*Math.PI;
}
}
16
Add Ellipse in OCP
public class AreaCalculator
{
public double Area(Shape[] shapes)
{
double area = 0;
foreach (Shape shape in shapes)
{
area += shape.Area();
}
return area;
}
}
18
19
20
Interface Segregation Principle
• Clients shouldn’t be
forced to depend on
methods they
do not use.
21
22
Dependency Inversion Principle
25
How DIP works?
26
Example: Without DIP
27
Example: Without DIP
public class ElectricPowerSwitch {
public LightBulb lightBulb;
public boolean on;
public ElectricPowerSwitch(LightBulb lightBulb) {
this.lightBulb = lightBulb;
this.on = false;
}
public boolean isOn() {
return this.on;
}
public void press(){
boolean checkOn = isOn();
if (checkOn) {
lightBulb.turnOff();
this.on = false;
} else {
lightBulb.turnOn();
this.on = true;
}
} 28
}
Example: DIP
public interface Switch {
boolean isOn();
void press();
}
29
Example: DIP
public class ElectricPowerSwitch implements Switch {
public Switchable client;
public boolean on;
public ElectricPowerSwitch(Switchable client) {
this.client = client;
this.on = false;
}
public boolean isOn() {
return this.on;
}
public void press(){
boolean checkOn = isOn();
if (checkOn) {
client.turnOff();
this.on = false;
} else {
client.turnOn();
this.on = true;
}
}
30
}
Example: DIP
public class Fan implements Switchable {
@Override
public void turnOn() {
System.out.println("Fan: Fan turned on...");
}
@Override
public void turnOff() {
System.out.println("Fan: Fan turned off...");
}
}
@Override
public void turnOff() {
System.out.println("LightBulb: Bulb turned off...");
}
}
31
Reference