Design Pattern Examples
Design Pattern Examples
ENEMYSHIP.JAVA
view sourceprint?
01
02
03
04
05
06
07
08
09
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
}
}
UFOENEMYSHIP.JAVA
01
02
03
04
05
06
07
08
09
10
11
public UFOEnemyShip(){
setName("UFO Enemy Ship");
setDamage(20.0);
}
}
ROCKETENEMYSHIP.JAVA
01
02
03
04
05
06
07
08
09
10
11
public RocketEnemyShip(){
setName("Rocket Enemy Ship");
setDamage(10.0);
}
}
ENEMYSHIPTESTING.JAVA
01
import java.util.Scanner;
02
03
04
05
06
07
08
09
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
if (userInput.hasNextLine()){
String typeOfShip = userInput.nextLine();
theEnemy = shipFactory.makeEnemyShip(typeOfShip);
if(theEnemy != null){
doStuffEnemy(theEnemy);
} else System.out.print("Please enter U, R, or B next time");
}
/*
EnemyShip theEnemy = null;
// Old way of creating objects
// When we use new we are not being dynamic
EnemyShip ufoShip = new UFOEnemyShip();
doStuffEnemy(ufoShip);
System.out.print("\n");
// ----------------------------------------// This allows me to make the program more dynamic
// It doesn't close the code from being modified
// and that is bad!
// Defines an input stream to watch: keyboard
Scanner userInput = new Scanner(System.in);
String enemyShipOption = "";
System.out.print("What type of ship? (U or R)");
if (userInput.hasNextLine()){
enemyShipOption = userInput.nextLine();
}
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
if (enemyShipOption == "U"){
theEnemy = new UFOEnemyShip();
} else
if (enemyShipOption == "R"){
theEnemy = new RocketEnemyShip();
} else {
theEnemy = new BigUFOEnemyShip();
}
doStuffEnemy(theEnemy);
// -------------------------------------------*/
}
// Executes methods of the super class
public static void doStuffEnemy(EnemyShip anEnemyShip){
anEnemyShip.displayEnemyShip();
anEnemyShip.followHeroShip();
anEnemyShip.enemyShipShoots();
}
}
BIGUFOENEMYSHIP.JAVA
01
02
03
04
05
public BigUFOEnemyShip(){
setName("Big UFO Enemy Ship");
06
07
08
09
10
11
setDamage(40.0);
}
}
ENEMYSHIPFACTORY.JAVA
06
07
08
09
10
11
12
13
14
if (newShipType.equals("U")){
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34