10.設計模式&OO原則概覽
阿新 • • 發佈:2018-12-16
-
程式碼
-
Duck
package com.desmond.codebase.designpattern.overview.v4; /** * @author presleyli * @date 2018/10/17 上午8:11 */ public abstract class Duck { private Flyable flyable; private Quackable quackable; public Flyable getFlyable() { return flyable; } public void setFlyable
-
MallrdDuck
package com.desmond.codebase.designpattern.overview.v4; /** * @author presleyli * @date 2018/10/17 上午8:12 */
-
RubberDuck
package com.desmond.codebase.designpattern.overview.v4; /** * @author presleyli * @date 2018/10/17 上午8:17 */ public class RubberDuck extends Duck { @Override public void display() { System.out.println("yellow"); } @Override public void quack() { this.getQuackable().quack(); } @Override public void swim() { super.swim(); } @Override public void fly() { this.getFlyable().fly(); } }
-
Flyable
package com.desmond.codebase.designpattern.overview.v4; /** * Created by presleyli on 2018/10/17. */ public interface Flyable { void fly(); }
-
CanFly
package com.desmond.codebase.designpattern.overview.v4; /** * @author presleyli * @date 2018/10/19 上午7:32 */ public class CanFly implements Flyable { @Override public void fly() { System.out.println("I can fly..."); } }
-
CannotFly
package com.desmond.codebase.designpattern.overview.v4; /** * @author presleyli * @date 2018/10/19 上午7:32 */ public class CannotFly implements Flyable { @Override public void fly() { // do nothing. } }
-
Quackable
package com.desmond.codebase.designpattern.overview.v4; /** * Created by presleyli on 2018/10/17. */ public interface Quackable { void quack(); }
-
CanQuack
package com.desmond.codebase.designpattern.overview.v4; /** * @author presleyli * @date 2018/10/19 上午7:33 */ public class CanQuack implements Quackable{ @Override public void quack() { System.out.println("I can quack..."); } }
-
CannotQuack
package com.desmond.codebase.designpattern.overview.v4; /** * @author presleyli * @date 2018/10/19 上午7:33 */ public class CannotQuack implements Quackable{ @Override public void quack() { // do nothing. } }
-
Main
package com.desmond.codebase.designpattern.overview.v4; /** * @author presleyli * @date 2018/10/17 上午8:14 */ public class Main { public static void main(String[] args) { MallrdDuck mallrdDuck = new MallrdDuck(); mallrdDuck.setFlyable(new CanFly()); mallrdDuck.setQuackable(new CannotQuack()); mallrdDuck.fly(); mallrdDuck.quack(); RubberDuck rubberDuck = new RubberDuck(); rubberDuck.setFlyable(new CanFly()); rubberDuck.setQuackable(new CanQuack()); rubberDuck.fly(); rubberDuck.quack(); } }
-
Output:
I can fly... I can fly... I can quack...
-