实现不同人、不同画笔、不同颜料三个类别的桥接
//把笔抽象出来
abstract class Brush {
protected Color c;
protected Person p;
//不同的笔和颜色有不同的实现方式,因此各自重写抽象方法。
public abstract void paint();
//颜色不需要抽象出来,它通过多态实现即可。
public void setColor(Color c) {
this.c = c;
}
public void setPerson(Person p){
this.p = p;
}
}
class BigBrush extends Brush {
@Override
public void paint() {
System.out.println(p.person + " use big brush paint " + c.color);
}
}
class SmallBrush extends Brush {
@Override
public void paint() {
System.out.println(p.person + " use small brush paint " + c.color);
}
}
//把颜色抽象出来
abstract class Color {
public String color;
}
class Red extends Color{
public Red(){
this.color = "red";
}
}
class Green extends Color{
public Green(){
this.color = "green";
}
}
class Blue extends Color{
public Blue(){
this.color = "blue";
}
}
abstract class Person {
public String person;
}
class Man extends Person{
public Man(){
this.person = "man";
}
}
class Woman extends Person{
public Woman(){
this.person = "woman";
}
}
/*
三个类别的桥接。降低耦合度
*/
public class Client {
public static void main(String[] args) {
//new一个大的笔
Brush brush = new BigBrush();
brush.setColor(new Red());
brush.setPerson(new Man());
brush.paint();
brush.setColor(new Green());
brush.setPerson(new Woman());
brush.paint();
//new一个小的笔
Brush brush1 = new SmallBrush();
brush1.setColor(new Blue());
brush1.setPerson(new Woman());
brush1.paint();
}
}
输出
man use big brush paint red
woman use big brush paint green
woman use small brush paint blue