桥接模式(设计模式_24)

桥接模式的定义就是,让抽象的部分与实现的部分分离,使得他们各种灵活的变化哦
可能这样见不好理解,其实简单的理解就把实现的部分进行了分类,耦合度减低了

以下看案例说明:


package com.oop.demo1;

/**
 * 抽象出动物抽象类
 * @author Liudeli
 *
 */
public abstract class Animal {

    /**
     * 抽象出动物打印行为
     */
    public abstract void method();

}
package com.oop.demo1;

/**
 * 定义动物抽象类对具体动物对象
 * @author Liudeli
 *
 */
public class Cat extends Animal{

    public void method() {
        System.out.println("Cat...");
    }

}
package com.oop.demo1;

/**
 * 定义动物抽象类对具体动物对象
 * @author Liudeli
 *
 */
public class Dog extends Animal{

    public void method() {
        System.out.println("Dog...");
    }

}
package com.oop.demo1;

/**
 * 抽象出一个人抽象类
 * @author Liudeli
 *
 */
public class Person {

    private Animal animal;

    public void setPerson(Animal animal) {
        this.animal = animal;
    }

    public Animal getPerson() {
        return animal;
    }

    public void getAnimal() {
        animal.method();
    }

}
package com.oop.demo1;

public class ManPerson extends Person{

    public void getAnimal() {
        getPerson().method();
    }

}
/**
 * 测试程序(桥接模式)
 * @author Liudeli
 *
 */
public class Main {

    public static void main(String[] args) {
        // 本来常规是这样来写的
        Animal animal = new Dog();
        animal.method();
        animal = new Cat();
        animal.method();

        /**
         * 以下就是用桥接模式进行了分类,从而减低耦合度
         */
        Person manPerson = new ManPerson();

        manPerson.setPerson(new Dog());
        manPerson.getAnimal();

        manPerson.setPerson(new Cat());
        manPerson.getAnimal();
    }

}

运行结果:
这里写图片描述


这里写图片描述


谢谢大家的观看,更多精彩技术博客,会不断的更新,请大家访问,
刘德利CSDN博客, http://blog.csdn.net/u011967006

原文地址:https://www.cnblogs.com/android-deli/p/10322191.html