设计模式-桥接bridge

1 使用场景

存在两个(多个)独立变化的维度,且这两个维度都需要进行扩展。

一般这2个变化的对象有一个主从关系。从的是依附的,没有不影响主的最基本的使用。

 

2 代码结构

   上面的主就是一个抽象类,里面关联从的变化对象。从是接口。

  

3 举例

   画图软件。先画出形状,为了丰富功能需要着色、音效等。

代码实现:

/**
 * 2个(多个)变化的维度 形状和颜色
 * 先有形状后再涂色、播放音效
 * 故需要关联颜色
 */
public abstract class Shape {
    //非私有 被继承
    IColor color;

    ISound sound;

    public void setColor(IColor color) {
        this.color = color;
    }

    public void setSound(ISound sound) {
        this.sound = sound;
    }

    public abstract void draw();
}

抽象类 :

public interface IColor {
    public void bepaint(String shape);
}

public interface ISound {
    public void play(String ring);
}

自然而然的需要实现抽象类的各个形状。

扫描二维码关注公众号,回复: 3636308 查看本文章
public class Circle extends Shape {
    @Override
    public void draw() {
        if (null != color) {
            color.bepaint("正方形");
        } else {
            System.out.println("无颜色");
        }

        if (null != sound) {
            sound.play("正方形");
        } else {
            System.out.println("无音效");
        }
    }
}
public class Rectangle extends Shape {
    @Override
    public void draw() {
        // 用null判断不优雅
        if (null != color) {
            color.bepaint("长方形");
        } else {
            System.out.println("无颜色");
        }

        if (null != sound) {
            sound.play("长方形");
        } else {
            System.out.println("无音效");
        }
    }
}

同理实现颜色、声音的实现类。

public class White implements IColor {
    @Override
    public void bepaint(String shape) {
        System.out.println("白色的" + shape);
    }
}

public class Black implements IColor {
    @Override
    public void bepaint(String shape) {
        System.out.println("黑色的" + shape);
    }
}


public class BirdRing implements ISound {
    @Override
    public void play(String shapName) {
        System.out.println(shapName + "鸟叫声");
    }
}

public class WaterRing implements ISound {
    @Override
    public void play(String shapName) {
        System.out.println(shapName + "水滴声");
    }
}


测试:public class Client {
    public static void main(String[] args) {
        //白色
        Shape square = new Circle();
        IColor white = new White();
        ISound birdRing = new BirdRing();
        //白色的正方形
        square.setColor(white);
        square.setSound(birdRing);
        square.draw();
        System.out.println("=========我是分割线================");
        //长方形
        Shape rectange = new Rectangle();
        rectange.setColor(white);
        rectange.draw();
    }

白色的正方形
正方形鸟叫声
=========我是分割线================
白色的长方形
无音效
}

猜你喜欢

转载自blog.csdn.net/f327888576/article/details/81977115
今日推荐