设计模式学习之路---Strategy(《Strategy模式的一个例子》改进)
说明:之前的那个source只是完成了答案,他只是说明strategy模式的一种分析过程(详见附件的试卷中的解释)!改进后的source从java代码的完整性和可读性上做了一些修饰。但是设计模式的学习是路漫漫的,希望自己能坚持到底!给自己加油先!!!/* Strategy */
import java.util.Scanner;
interface FlyBehavior {
public void fly();
}
interface QuackBehavior {
public void quack();
}
class FlyWithWings implements FlyBehavior{
public void fly(){
System.out.println("使用翅膀飞行~~~");
}
}
class FlyNoWay implements FlyBehavior {
public void fly(){
System.out.println("偶的飞行特征:偶啊,不能飞行,可怜啊~~~");
}
}
class Quack implements QuackBehavior{
public void quack(){
System.out.println("偶的发声特征:偶啊,发出\'嘎嘎\'声,不怎么好听!5555555~~~");
}
}
class Squeak implements QuackBehavior {
public void quack(){
System.out.println("偶的发声特征:偶啊,发出与空气与橡皮摩擦声!~~~");
}
}
class QuackNoWay implements QuackBehavior {
public void quack(){
System.out.println("偶的发声特征:偶啊,不能发声,是最可怜的啦,555555555~~~");
}
}
abstract class Duck{
protected FlyBehavior flyBehavior;
protected QuackBehavior quackBehavior;
public void fly(){
flyBehavior.fly();
}
public void quack(){
quackBehavior.quack();
}
public abstract void display();
}
class OneDuck extends Duck{
private String duckName;
public OneDuck(String duckName){
this.duckName = duckName;
flyBehavior = new FlyNoWay();
quackBehavior = new Squeak();
}
public void display() {
System.out.println("偶是 " + duckName + "~~~");
flyBehavior.fly();
quackBehavior.quack();
}
}
public class Strategy {
private static String duckName = "";
public static void MainMenu(){
System.out.println("@@@@@@@@@@@@@@@@@@@");
System.out.println("1.RubberDuck");
System.out.println("2.CottonoDuck");
System.out.println("3.RedHeadDuck");
System.out.println("4.MallardDuck");
System.out.println("@@@@@@@@@@@@@@@@@@@");
System.out.println();
System.out.println("请选择一种鸭子种类");
Scanner reader = new Scanner(System.in);
int i = reader.nextInt();
switch(i){
case 1:
duckName = "RubberDuck";
break;
case 2:
duckName = "CottonoDuck";
break;
case 3:
duckName = "RedHeadDuck";
break;
case 4:
duckName = "MallardDuck";
break;
default:
break;
}
if( i > 4 || i < 1)
System.out.println("你的选择错误!");
else
(new OneDuck(duckName)).display();
}
public static void main(String[] args) {
MainMenu();
}
}