码迷,mamicode.com
首页 > 其他好文 > 详细

会点模式,要有大局观~~~

时间:2015-05-10 18:46:29      阅读:114      评论:0      收藏:0      [点我收藏+]

标签:

总的原则是像变形金刚一样,各个组件拆到刚好适合业务为止。。

拆得太细,会迷失。

耦合性太强的话,会不能适应变化~~

MiniDuckSimulator.java

abstract class Duck {
    
    FlyBehavior flyBehavior;
    QuackBehavior quackBehavior;

    public abstract void display();
    
    public void performFly() {
        flyBehavior.fly();
    }
    
    public void performQuack() {
        quackBehavior.quack();
    }
    public void swim() {
        System.out.println("All duck float, even decoys!");
    }
    
    public void setFlyBehavior(FlyBehavior fb) {
        flyBehavior = fb;
    }
    public void setQuackBehavior(QuackBehavior qb) {
        quackBehavior = qb;
    }
}


interface FlyBehavior{
    public void fly();
}

class FlyWithWings implements FlyBehavior {
    public void fly() {
        System.out.println("I‘m flying!");
    }
}

class FlyNoWay implements FlyBehavior {
    public void fly() {
        System.out.println("I can‘t fly!");
    }
}

class FlyRocketPowered implements FlyBehavior {
    public void fly() {
        System.out.println("I‘m flying with a rocket!");
    }
}

interface QuackBehavior {
    public void quack();
}

class Quack implements QuackBehavior {
    public void quack() {
        System.out.println("Quack");
    }
}

class MuteQuack implements QuackBehavior {
    public void quack() {
        System.out.println("<< Silence >>");
    }
}

class Squeak implements QuackBehavior {
    public void quack(){
        System.out.println("Squeak");
    }
}

class MallardDuck extends Duck {
    public MallardDuck() {
        quackBehavior = new Quack();
        flyBehavior = new FlyWithWings();
    }
    public void display(){
        System.out.println("I‘m a real Mallard duck");
    }
}

class ModelDuck extends Duck {
    public ModelDuck() {
        flyBehavior = new FlyNoWay();
        quackBehavior = new Quack();
    }
    public void display() {
        System.out.println("I‘m a model duck!");
    }
}

public class MiniDuckSimulator {

    public static void main(String[] args) {
        // TODO Auto-generated method stub
        Duck mallard = new MallardDuck();
        mallard.performQuack();
        mallard.performFly();
        mallard.swim();
        
        Duck model = new ModelDuck();
        model.performFly();
        model.setFlyBehavior(new FlyRocketPowered());
        model.performFly();

    }

}

Quack
I‘m flying!
All duck float, even decoys!
I can‘t fly!
I‘m flying with a rocket!

技术分享

会点模式,要有大局观~~~

标签:

原文地址:http://www.cnblogs.com/aguncn/p/4492508.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!