Head First 設計模式讀書筆記
阿新 • • 發佈:2019-02-08
public class DuckTest {
public static void main(String[] args) {
MallardDuck duck = new MallardDuck();
duck.setFlyBehavior(new FlyWithWings());
duck.setQuackBehavior(new Quack());
duck.perFly();
duck.perQuack();
}
}
interface FlyI{
void fly();
}
class FlyWithWings implements FlyI{
public void fly() {
System.out.println("fly with wings");
}
}
interface QuackI{
void quack();
}
class Quack implements QuackI{
public void quack() {
System.out.println("呱呱");
}
}
abstract class Duck{
FlyI flyBehavior; //委託給FlyI介面具體實現處理飛行為
QuackI quackBehavior; //委託給QuackI介面具體實現處理叫行為
abstract public void display();
//動態設定飛行為
public void setFlyBehavior(FlyI flyBehavior) {
this.flyBehavior = flyBehavior;
}
//動態設定叫行為
public void setQuackBehavior(QuackI quackBehavior) {
this.quackBehavior = quackBehavior;
}
public void perFly(){
flyBehavior.fly();
}
public void perQuack(){
quackBehavior.quack();
}
}
class MallardDuck extends Duck{
public void display() {
System.out.println("綠頭鴨");
}
}
public static void main(String[] args) {
MallardDuck duck = new MallardDuck();
duck.setFlyBehavior(new FlyWithWings());
duck.setQuackBehavior(new Quack());
duck.perFly();
duck.perQuack();
}
}
interface FlyI{
void fly();
}
class FlyWithWings implements FlyI{
public void fly() {
System.out.println("fly with wings");
}
}
interface QuackI{
void quack();
}
class Quack implements QuackI{
public void quack() {
System.out.println("呱呱");
}
}
abstract class Duck{
FlyI flyBehavior; //委託給FlyI介面具體實現處理飛行為
QuackI quackBehavior; //委託給QuackI介面具體實現處理叫行為
abstract public void display();
//動態設定飛行為
public void setFlyBehavior(FlyI flyBehavior) {
this.flyBehavior = flyBehavior;
}
//動態設定叫行為
public void setQuackBehavior(QuackI quackBehavior) {
this.quackBehavior = quackBehavior;
}
public void perFly(){
flyBehavior.fly();
}
public void perQuack(){
quackBehavior.quack();
}
}
class MallardDuck extends Duck{
public void display() {
System.out.println("綠頭鴨");
}
}