設計模式:行為模式
阿新 • • 發佈:2018-11-30
/** * 行為模式。 * @author Bright Lee */ public class BehaviorPattern { public static void main(String[] args) { Animal animal = null; animal = new Dog(); animal.setCallBehavior(new WangWangCallBehavior()); animal.call(); animal = new Cat(); animal.setCallBehavior(new MiaoMiaoCallBehavior()); animal.call(); } } class Animal { protected CallBehavior callBehavior; public void call() { callBehavior.call(); } public void setCallBehavior(CallBehavior callBehavior) { this.callBehavior = callBehavior; } } class Dog extends Animal { public Dog() { } } class Cat extends Animal { public Cat() { } } interface CallBehavior { void call(); } class WangWangCallBehavior implements CallBehavior { public void call() { System.out.println("汪汪!!"); } } class MiaoMiaoCallBehavior implements CallBehavior { public void call() { System.out.println("喵喵!!"); } }
輸出結果:
汪汪!!
喵喵!!