* 狀態模式
* 使用繼承表達行爲間的差異,並用字段表達狀態上的變化
* 通過繼承得到3個不同的類,來表達show()方法的差異;而Starship通過運用組合使自己的狀態發生變化,
* 這種情況下,狀態的改變也就產生了行爲的改變
*/
class AlertStatus{
public void show(){}
}
class AlertRed extends AlertStatus
{
@Override
public void show() {
System.out.println("RED!");
}
}
class AlertBlue extends AlertStatus
{
@Override
public void show() {
System.out.println("BLUE!");
}
}
class AlertYellow extends AlertStatus
{
@Override
public void show() {
System.out.println("YELLOW!");
}
}
public class Starship {
AlertStatus as = new AlertStatus();
public void changeToRed()
{
as = new AlertRed();
}
public void changeToYellow()
{
as = new AlertYellow();
}
public void changeToBlue()
{
as = new AlertBlue();
}
public void showStar()
{
as.show();
}
public static void main(String[] args) {
Starship ss = new Starship();
ss.showStar();
ss.changeToBlue();
ss.showStar();
ss.changeToYellow();
ss.showStar();
ss.changeToRed();
ss.showStar();
}
}
/*
* Output:
* BLUE!
* YELLOW!
* RED!
*
*/