这段时间看《Head First设计模式》,今晚按第一章的描述写了个测试程序。程序代码以下:
===================================
Duck.java
public abstract class Duck {
public FlyBehavior flyBehavior;
public QuackBehavior quackBehavior;
public Duck(){}
public abstract void display();
public void swim()
{
System.out.println("All ducks float,even decoys!");
}
public void performQuack()
{
flyBehavior.fly();
}
public void performFly()
{
quackBehavior.quack();
}
}
===================================
FlyBehavior.java
public interface FlyBehavior {
public void fly();
}
===================================
FlyNoWay.java
public class FlyNoWay implements FlyBehavior {
public void fly() {
// TODO Auto-generated method stub
System.out.println("I can't fly!!");
}
}
===================================
FlyWithWings.java
public class FlyWithWings implements FlyBehavior {
public void fly() {
// TODO Auto-generated method stub
System.out.println("I'm flying!!");
}
}
===================================
QuackBehavior.java
public interface QuackBehavior {
public void quack();
}
===================================
Quack.java
public class Quack implements QuackBehavior {
public void quack() {
// TODO Auto-generated method stub
System.out.println("Quack");
}
}
===================================
Squeak.java
public class Squeak implements QuackBehavior {
public void quack() {
// TODO Auto-generated method stub
System.out.println("Squeak");
}
}
===================================
MuteQuack.java
public class MuteQuack implements QuackBehavior {
public void quack() {
// TODO Auto-generated method stub
System.out.println("<<Silence>>");
}
}
===================================
MallardDuck.java
public class MallardDuck extends Duck {
public MallardDuck()
{
flyBehavior=new FlyWithWings();
quackBehavior=new Quack();
}
@Override
public void display() {
// TODO Auto-generated method stub
System.out.println("I'm a real Mallard duck");
}
}
===================================
ModelDuck.java
public class ModelDuck extends Duck {
public ModelDuck()
{
flyBehavior=new FlyNoWay();
quackBehavior=new Quack();
}
@Override
public void display() {
// TODO Auto-generated method stub
System.out.println("I'm a model duck");
}
}
===================================
DuckSimulator.java
public class DuckSimulator {
public static void main(String[] args) {
// TODO Auto-generated method stub
Duck mallard=new MallardDuck();
mallard.performFly();
mallard.performQuack();
Duck model=new ModelDuck();
model.performFly();
model.performQuack();
}
}
===================================
输出结果以下:
Quack
I'm flying!!
Quack
I can't fly!!
===================================
以上就是《Head First设计模式》里第一个设计模式的程序代码,有空再写下解释。